Possible Duplicate:
Static fields on a null reference in Java
I understand that static methods are on class level. So I am aware that I do not need to create instance to call static methods. But I am also aware that I can call static method LIKE an instance method. This is where I am confused, because I was expecting a NullPointerException while calling the static method from the null object (as in calling instance method). I would really appreciate some explanation on why I was wrong to expect a NullPointerException here.
Here is the sample code:
public class SampleClass {
public static int getSumStatic(int x, int y){
return x+y;
}
public int getDifferenceInstance(int x, int y){
return x-y;
}
}
public class TestClass {
public static void main (String[] args){
SampleClass sc=null;
System.out.println(SampleClass.getSumStatic(2, 2)); //as expected
//I was expecting NullPointerException in the next line, since I am accessing null object
System.out.println(sc.getSumStatic(4,5)); //static method , executes perfectly
System.out.println(sc.getDifferenceInstance(6,4));//throws NullPointerException
}
}
Calling a static method through an instance does not require the instance to be there. As long as the compiler is able to determine the type of the variable, it makes the equivalent call statically after evaluating the
scexpression and discarding the result:From the Java Language Specification: