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

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

问题描述

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

一般来说这也是一个很好的做法。即使普通的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.

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

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