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?
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"...
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