What happens when a static method is invoked using

2019-01-14 23:22发布

问题:

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?

回答1:

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.



回答2:

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



回答3:

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.

When a target reference is computed and then discarded because the invocation mode is static, the reference is not examined to see whether it is null:

class Test1 {
    static void mountain() {
        System.out.println("Monadnock");
    }
    static Test1 favorite(){
        System.out.print("Mount ");
        return null;
    }
    public static void main(String[] args) {
        favorite().mountain();
    }
}


回答4:

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.



回答5:

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