Constructor not being called
I was asked to explain why the line
Code:
System.out.println("" + x[2].getN());
wont work. I figure the constructor is not being triggered but the why, beats me. Anyone care to explain?
Code:
class Num{
private int n;
public int getN(){ return n;}
public Num( ){ n = 4; }
}
public class Main {
public static void main( String[] args){
Num [] x = new Num[7];
System.out.println("" + x.length);
System.out.println("" + x[2].getN());
}
}
Re: Constructor not being called
If I'm not mistaken you're probably getting a NullPointerException?
You've shown that Num holds an array of Num objects but you haven't assigned a Num object to the array
Try
Code:
Num [] x = new Num[7] ;
int i = 0 ;
while(i < 7)
{
x[i] = new Num() ;
i++ ;
}
this should call the empty constructor of the object Num to the array and create the object of it.
The "=" the assigns the object to your array. Use a loop then for the rest of the elements. The line should work then!
Sorry if this confuses you it's the first time I've provided advice and it's the best I can explain it to you :-)
Re: Constructor not being called
I think you made a perfect explanation.
Expression
Code:
Num [] x = new Num[7]
only tells de JVM to allocate a block of contiguous memory. Num constructor is NOT called.
Albert.