I wrote this program in Java
public class Why {
public static void test() {
System.out.println("Passed");
}
public static void main(String[] args) {
Why NULL = null;
NULL.test();
}
}
I read that invoking a method on a null object causes NullPointerException, and yet the above program doesn’t? Why is this? Am I not understanding something correctly?
test()is astaticmethod. Astaticmember belongs to the type, and do not require an instance to access.A
staticmember should ONLY be accessed via a type expression. That is, you should’ve written it as follows:Java does allow you to access a
staticmember via an object reference expression, butthis is VERY misleading, since this is NOT the actual semantics of a
staticmember access.When accessing a
staticmember through an object reference expression, only the declared type of the reference matters. This means that:null, since no instance is requirednull, it doesn’t matter what the runtime type of the object is, there is no dynamic dispatch!!!As you can see, the exact opposites are true on both points for instance member access. This is why
staticmembers should NEVER be accessed in a “non-static” way, because it gives a very misleading appearance on what it’s actually doing.Related questions
thisis crucial!)