Reputation: 2813
public class Main
{
public static void main(String []ar)
{
A m = new A();
System.out.println(m.getNull().getValue());
}
}
class A
{
A getNull()
{
return null;
}
static int getValue()
{
return 1;
}
}
I came across this question in an SCJP book. The code prints out 1
instead of an NPE as would be expected. Could somebody please explain the reason for the same?
Upvotes: 16
Views: 393
Reputation: 41200
System.out.println(m.getNull().getValue()); this line of code is same as System.out.println(A.getValue());
as because getValue() method is static and and all static call initiate at compile time in java. so it does not produce any error once you make getValue() in non static this will produce error as because it will be called at run time
Upvotes: 1
Reputation: 5226
getNull function returns an A object. getValue is declared as static, and just needs class_name to function, as in A.getValue(). Because getNull returns (in fact) an A object...you will get 1
Upvotes: 1
Reputation: 328608
It behaves as it should according to the Java Language Specification:
a null reference may be used to access a class (static) variable without causing an exception.
Upvotes: 18
Reputation: 346300
Static method calls are resolved at compile time. The Compiler sees that getNull()
has a return value of type A
which has a static getValue()
method (and no instance method of the same name), so in the bytecode, the actual return value of getNull()
is ignored and A.getValue()
is called.
Upvotes: 6
Reputation: 1500515
Basically you're calling a static method as if it were an instance method. That just gets resolved to a static method call, so it's as if you'd written:
A m = new A();
m.getNull();
System.out.println(A.getValue());
IMO the fact that your code is legal at all is a design flaw in Java. It allows you to write very misleading code, with Thread.sleep
as an example I always use:
Thread thread = new Thread(someRunnable);
thread.start();
thread.sleep(1000);
Which thread does that send to sleep? The current one, "of course"...
Upvotes: 22