In all the initializers, forward referencing of variables is not allowed. Forward referencing of methods is allowed.
Forward referencing is known as accessing a variable or method that is defined forward in the sequence. Although while initialization takes place the forward referencing of variables are not allowed but forward referening of methods is allowed.
That is true.
Instance variables are initialized in the sequence in which they appear in the code. So if you try to initialize a variable with another that is down to the prior on, compiler generates error, because upto this level the varialble may not be initialized. Instance variables are initialized from top to down or say that in order they appear in the program.
The overall fact is, you can’t use a variable until it is initialized, although there may be scenario when you are allowed to assign it a value.
int i=j; //compiler error, can’t use a field before it is initialized.
int j=5;
But if j is static, no problemo!
int i=j; //OK
static int j=5;
This is only because static variables initialization takes place when class is loaded, so there when instance variable I is initialized j already exists well initialized with value 5.
But if you are initializing a variable using a method return type, its ok.
class ForwardRef {
int k = getI();
int i=5;
public int getI() {
return i;
}
public static static void main(String[] args) {
System.out.println(“k = “ + new ForwardRef().k);
}
}
This prints 0; We are simple fooled by forward referencing. You can point here the previous sequence related definitions. Variable I has not been initialized at the point it is used. So default value of k is printed.
See another scenario:
class ForwardRef {
{
i=10;
}
int i=5;
}
Why this? Simple rule; we are not using variable i but simply assigning it a value. And you know i=10 is going to be executed prior to i=5 executes because of the ordering of code they appear in the program.
One more case:
class Outerclass {
class innerclass {
int a=b;
}
int b=10;
}
Here the code compiles just fine. You recall that the non static inner class is associated with the containing class so, the b would be lot before initialized. You must have instance of the container class when you want to instantiate the inner class object so there is no problem either in using the outer class member variable or just initializing it another value.
Thursday, April 5, 2007
Subscribe to:
Posts (Atom)