Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when a static method is invoked using a null object reference?

public class CallingStaticMethod {
public static void method() {
    System.out.println("I am in method");
}
public static void main(String[] args) {
    CallingStaticMethod csm = null;
    csm.method();
   }
}

Can someone explain how the static method is invoked in the above code?

like image 648
java_geek Avatar asked Feb 08 '10 17:02

java_geek


2 Answers

It's been optimized away by the compiler, simply because having an instance of the class is not necessary. The compiler basically replaces

csm.method();

by

CallingStaticMethod.method();

It's in general also a good practice to do so yourself. Even the average IDE would warn you about accessing static methods through an instance, at least Eclipse does here.

like image 183
BalusC Avatar answered Oct 01 '22 15:10

BalusC


Java allows you to use a Class instance to call static methods, but you should not confuse this allowance as if the method would be called on the instance used to call it.

instance.method();

is the same as

Class.method();

like image 25
Dan Avatar answered Oct 01 '22 13:10

Dan