Static Method Invocation on Null References: Why the Surprise
When working with Java, one commonly encounters the rule that invoking a method on a null reference triggers a NullPointerException. However, consider the following code snippet:
<code class="java">public class Why { public static void test() { System.out.println("Passed"); } public static void main(String[] args) { Why NULL = null; NULL.test(); // Doesn't throw NullPointerException } }</code>
To our surprise, the above program doesn't throw a NullPointerException. Why is this the case?
Understanding Static Methods
The key to understanding this behavior lies in the nature of static methods. Static members, including methods, belong to the class, not to specific instances. They can be accessed directly via the type name without the need for an object reference.
In the example above, test() is a static method. When it is invoked using NULL.test(), Java treats this as invoking Why.test() because the actual object reference is irrelevant.
Static Access through Object References (Avoid!)
While Java allows accessing static members through object references, this practice is strongly discouraged. It can lead to confusion, as it conceals the actual semantics of static member access.
What Matters in Static Member Access
When accessing a static member through an object reference expression, only the declared type of the reference matters. This implies that:
Related Considerations
The above is the detailed content of Why Doesn\'t Invoking a Static Method on a Null Reference Throw a NullPointerException?. For more information, please follow other related articles on the PHP Chinese website!