当使用空对象引用调用静态方法时会发生什么? [英] What happens when a static method is invoked using a null object reference?

查看:25
本文介绍了当使用空对象引用调用静态方法时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

CallingStaticMethod.method();

一般来说,自己这样做也是一种很好的做法.即使是普通的 IDE 也会警告您通过实例访问静态方法,至少 Eclipse 在这里会这样做.

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.

这篇关于当使用空对象引用调用静态方法时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆