static
members (static
fields or static
methods) in Java are associated with their respective class rather than the objects of this class. The following code attempts to access a static field on a null
reference.
public class Main
{
private static final int value = 10;
public Main getNull()
{
return null;
}
public static void main(String[] args)
{
Main main=new Main();
System.out.println("value = "+main.getNull().value);
}
}
Although main.getNull()
returns null
, it works and displays value = 10
. How does this code work?
Accessing a
static
member with the class name is legal, but its no were written that one cannot access thestatic
member using the object reference variable. So it works over here.A
null
object reference variable is allowed to access astatic
class variable without throwing an exception either at compile or run time.When ever you access a static variable or method with objects at compile time it converted to Class name. eg:
It will print the value of static variable value because at compile time It will be converted to
Proof:
download decompiler and Decompile your .class file to .java file and you can see all static methods or variable referred object name is automatically replaced by class name.
Static variable and method always belong to class. So when ever we create any object only non static variable and methods goes to heap along with object but static resides in method area with class. That's why when ever we try to access a static variable or method it converted to class name dot variable or method name.
Please refer below link for more detail.
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Because, as you said, static fields are not associated with an instance.
The ability to access static fields from an instance reference (as you are doing) is merely a syntactic sugar and has no additional meaning.
Your code compiles to
That behaviour is specified in the Java Language Specification:
In more details, a static field evaluation, such as
Primary.staticField
works as follows (emphasis mine) - in your case,Primary = main.getNull()
: