Take a look at below code:
class Foo{
public static int x = 1;
}
class Bar{
public static void main(String[] args) {
Foo foo;
System.out.println(foo.x); // Error: Variable 'foo' might not have been initialized
}
}
As you see while trying to access static field x
via an uninitialized local variable Foo foo;
code foo.x
generates compilation error: Variable 'foo' might not have been initialized
.
It could seem like this error makes sense, but only until we realize that to access a static
member the JVM doesn't actually use the value of a variable, but only its type.
For instance I can initialize foo
with value null
and this will let us access x
without any problems:
Foo foo = null;
System.out.println(foo.x); //compiles and at runtime prints 1!!!
Such scenario works because compiler realizes that x
is static and treats foo.x
as if it was written like Foo.x
(at least that is what I thought until now).
So why compiler suddenly insists on foo
having a value which it will NOT use at all?
Disclaimer: This is not code which would be used in real application, but interesting phenomenon which I couldn't find answer to on Stack Overflow, so I decided to ask about it.
static
member compiler doesn't use value of variable but its type. We can even write((Foo)null).x
and this will compile and work because compiler will recognize thatx
is static (unless I misunderstood your comment).foo.x
) should have been a compiler error when Java was first created. Sadly, that ship sailed over 25 years ago and would be a breaking change if they changed it now.Foo.x
is preferred (which is why we usually get compilation warning when we attempt to use variantfoo.x
).