public class Why {
public static void test() {
System.out.println("Passed");
}
public static void main(String[] args) {
Why NULL = null;
NULL.test();
}
}
test() is a static method. A static member belongs to the type, and do not require an instance to access.
A static member should ONLY be accessed via a type expression. That is, you should’ve written it as follows:
Why.test(); // always invoke static method on the type it belongs to!
Java does allow you to access a static member via an object reference expression, but this is VERY misleading, since this is NOT the actual semantics of a static member access.
Why aNull = null; aNull.test(); // DO NOT EVER DO THIS! // invokes Why.test(), does NOT throw NullPointerException
When accessing a static member through an object reference expression, only the declared type of the reference matters. This means that:
- It doesn’t matter if the reference is actually null, since no instance is required
- If the reference is not null, it doesn’t matter what the runtime type of the object is, there is no dynamic dispatch!!!