Reputation: 753
Why is this code a compilation error?
class Test1{
static {
System.out.println(x);
}
static int x = 10;
}
While the below code compiles and runs fine?
class Test2{
static int x = 10;
static {
m1();
System.out.println("base SB");
}
public static void main(String args[]){
m1();
System.out.println("base main method");
}
public static void m1(){
System.out.println(y);
}
static int y = 20;
}
If it declares y here, why not in the previous code. The output of below code is:
0
base SB
20
base main method
I think Java does not support forward referencing.
Upvotes: 0
Views: 87
Reputation: 44250
Your second test case prints zero first which I would assume would not be idiomatic for most people.
This is simply a case of the compiler not being smart enough to catch a probable mistake which you have made.
It is able to detect the forward reference in the first case -- lucky! If it didn't, your program would have printed zero at runtime since the variable would not have been initialized yet. So the compiler saved you from a probable bug.
It is not able to detect it in the second case, since you have introduced a level of indirection with the additional method call to m1
-- unlucky!
In an ideal world, the second code sample wouldn't compile either.
Upvotes: 2
Reputation: 140544
It may be an unsatisfying answer, but this is just how the language was defined, specifically here.
The restrictions above are designed to catch, at compile time, circular or otherwise malformed initializations
But you can get around the restriction quite easily like in the question, or just by using Test21.x
instead of just x
, so it is not particularly robust:
class Test21{
static {
// This is legal, but it is uninitialized, and thus prints 0.
System.out.println(Test21.x);
}
static int x=10;
}
On balance, it is probably better to force you to jump through a small hoop, to make you stop and think about what you are doing, and only to proceed if you really intend to do that.
Ultimately, the language can't entirely stop you shooting yourself in the foot. It can only make it harder to do so.
Upvotes: 4