Recently I was going through a page on javarevisited and found a block of code which asked the readers to determine what would be the output for it...
Though I got the output I am not satisfied with the result (WHICH CAME OUT TO BE "Hello") since I don't know how a static member is accessed from a null reference. What's happening in the background?
public class StaticDEMO {
private static String GREET = "Hello";
public static void main(String[] args) {
StaticDEMO demo = null;
System.out.println(demo.GREET);
// TODO code application logic here
}
}
This works because the JVM knows you are trying to access a static member on a specific class. Because you had to declare demo
as a specific class (in this case a StaticDEMO
), it knows to use that to find GREET
.
To be clear, you don't run into this often (I actually had to type this code in to verify it, I can't say I've ever seen this). Mainly, it's good practice to always refer to static fields by their class, not an object instance (which may be null, as we can see!).
Meaning, prefer this:
System.out.println(StaticDEMO.GREET);
EDIT
I found a reference to this in the Java Specification: Chapter 15, Section 11: Field Access Expressions.
Example 15.11.1-2. Receiver Variable Is Irrelevant For static Field Access
The following program demonstrates that a null reference may be used to access a class (static) variable without causing an exception
[example not shown here for brevity]
Any method which is being decorated as static in Java means, that method is a class level memeber. That means, you do not need an object to accss static members. The static method/variable is maintained by the Class itself, and not by any instance of the class. Here in your example, the compiler already knows that the member is static member and it doesn't need any instance to access that static method.
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