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?
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.
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();
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