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?
Well this is perfectly ok. The static method is not being accessed by the object instance of class A. Either you call it by the class name or the reference, the compiler will call it through an instance of the class java.lang.Class.
FYI, each class(CallingStaticMethod in the above illustration) in java is an instance of the class 'java.lang.Class'. And whenever you define a class, the instance is created as java.lang.Class CallingStaticMethod = new java.lang.Class();
So the method is called on 'CallingStaticMethod ' and so null pointer exception will not occur.
Hope this helps.
The java language specification says the reference get's evaluated, then discarded, and then the static method gets invoked.
15.12.4.1. Compute Target Reference (If Necessary)
This is the same behavior when you use the
this
reference to call a static method.this
gets evaluated then discarded then the method is called.There is even an example in the specification similar to your example.
Yes we can. It will throw NullPointerException only if we are calling non static method with null object. If method is static it will run & if method is non static it will through an NPE...
To know more click here...
It's been optimized away by the compiler, simply because having an instance of the class is not necessary. The compiler basically replaces
by
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.
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();