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

查看:28
本文介绍了为什么在空引用上调用(静态)方法不会抛出 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.

static 成员应该通过类型表达式访问.也就是说,你应该这样写:

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 成员,但是这是非常误导,因为这不是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 成员应该NEVER 以非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?

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

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