What happens when a static method is invoked using

2019-01-14 22:54发布

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?

5条回答
不美不萌又怎样
2楼-- · 2019-01-14 23:21

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.

查看更多
爷、活的狠高调
3楼-- · 2019-01-14 23:30

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楼-- · 2019-01-14 23:42

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

查看更多
唯我独甜
5楼-- · 2019-01-14 23:43

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.

查看更多
叼着烟拽天下
6楼-- · 2019-01-14 23:43

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

查看更多
登录 后发表回答