I have the following code
public class Test {
static String mountain = "Everest";
static Test favorite() {
System.out.print("Mount ");
return null;
}
public static void main(String[] args) {
System.out.println(favorite().mountain);
}
}
I thought it would raise a NPE
but it is giving Mount Everest
as output can anyone clarify?
It just so happens that you can access static members on object references. In that case, the member is resolved according to the type of the reference, not its value.
The Java Language Specification says this about field access of static
members
If the field is a non-blank final field, then the result is the value of the specified class variable in the class or interface that is the type of the Primary expression.
If the field is not final, or is a blank final and the field access occurs in a constructor, then the result is a variable, namely, the specified class variable in the class that is the type of the Primary expression.
So the Primary, the instance, does not matter.
When you access a static
member on an instance of a class, the Java compiler completely ignores the runtime value (and even class) of the variable and uses the member belonging to the declared class. In this case, your code is equivalent to:
favorite();
System.out.println(Test.mountain);
Even if you had code like this:
public class SubTest extends Test {
static String mountain = "Kilimanjaro";
}
...
Test foo = new SubTest();
System.out.println(foo.mountain);
you'll still get the value on the Test
class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With