Author Topic:   Another qstn for you all... Just to enforce the point..
maha anna
bartender
posted March 10, 2000 08:00 AM             
Another qstn for you all... Just to enforce the point..
I know, most of MUST be knowing this already. But recently I didn't find any discussions related to this. So I am posting this here.
regds
maha anna.
Which version of class Test compiles and runs successfully?

class Test {
static int i = peek();
static int peek() { return j; }
static int j = 1;
public static void main(String[] args) {

}

}
class Test {
static int i = j;
static int peek() { return j; }
static int j = 1;
public static void main(String[] args) {

}
}

MEENU
unregistered
posted March 10, 2000 08:15 AM           
Hi Maha,
I tried your code with JVM. The first part compiles and runs fine while the second one gives compilation error,"Can't make forward reference to j".
I don't understand why both of them are behaving this way?
Your help will be much appreciated.
Thanks.

maha anna
bartender
posted March 10, 2000 12:07 PM             
The static/instance floating block initialization and class vars intializations are done in the SAME ORDER as they appear in a java program. The rule for this initialization is ,

1. The initialization expression on the RHS(RightHandSide) of any assignment statement SHOULD NOT DIRECTLY refer to another var which comes afterwards (below). Otherwise the compiler complains that it is a forward reference, which you can not do.

2. But acesses to class variables by methods are not checked in this way. You CAN do forward reference THROUGH methods. In this case the pre-defined value of the forwarded ref , which is the DEFAULT VALUE is used.
So in the foll. code peek() method returns the DEFAULT value of j which is 0 (not 1)is returned. Because the assignment of j comes BELOW the defn. of peek() method.
regds
maha anna


class Test {
static int i = peek();
static int peek() {
return j;
}
static int j = 1;

public static void main(String[] args) {
}
}

Meenu
unregistered
posted March 13, 2000 07:24 AM           
Thanks a bunch Maha for detailed explanation.

|