为什么在null引用上调用(静态)方法不会抛出NullPointerException? [英] How come invoking a (static) method on a null reference doesn't throw NullPointerException?

查看:115
本文介绍了为什么在null引用上调用(静态)方法不会抛出NullPointerException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Java编写了这个程序

I wrote this program in Java

public class Why {

  public static void test() {
    System.out.println("Passed");
  }

  public static void main(String[] args) {
    Why NULL = null;
    NULL.test();
  }

}

我读到了调用方法 null 对象导致 NullPointerException ,但上述程序却没有?为什么是这样?我不能正确理解某些内容吗?

I read that invoking a method on a null object causes NullPointerException, and yet the above program doesn't? Why is this? Am I not understanding something correctly?

推荐答案

test()是一个 static 方法。 static 成员属于该类型,并且不需要实例访问。

test() is a static method. A static member belongs to the type, and do not require an instance to access.

A static 成员应通过类型表达式访问 ONLY 。也就是说,您应该按如下方式编写:

A static member should ONLY be accessed via a type expression. That is, you should've written it as follows:

Why.test(); // always invoke static method on the type it belongs to!

Java允许您访问 static 成员通过对象引用表达式,但
这是非常误导,因为这是 NOT static 会员访问。

Java does allow you to access a static member via an object reference expression, but this is VERY misleading, since this is NOT the actual semantics of a static member access.

Why aNull = null; 
aNull.test(); // DO NOT EVER DO THIS!
// invokes Why.test(), does NOT throw NullPointerException

访问 static 成员通过对象引用表达式,只有声明的引用类型才有意义。这意味着:

When accessing a static member through an object reference expression, only the declared type of the reference matters. This means that:


  • 如果引用实际上是 null 并不重要,因为不需要实例

  • 如果引用不是 null ,那么对象的运行时类型是什么并不重要,没有动态调度 !!!

  • It doesn't matter if the reference is actually null, since no instance is required
  • If the reference is not null, it doesn't matter what the runtime type of the object is, there is no dynamic dispatch!!!

正如您所看到的,确切的对立面是正确的两个点例如成员访问。这就是 static 成员从不以非 - 静态方式访问的原因,因为它给它实际上做的事情带来了非常误导性的外观。

As you can see, the exact opposites are true on both points for instance member access. This is why static members should NEVER be accessed in a "non-static" way, because it gives a very misleading appearance on what it's actually doing.

  • Why doesn't Java allow overriding of static methods ? (understanding this is crucial!)
  • Why isn’t calling a static method by way of an instance an error for the Java compiler?

这篇关于为什么在null引用上调用(静态)方法不会抛出NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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