什么情况下,空引用null调用方法不报空指针异常?

来源:互联网 发布:数据波 编辑:程序博客网 时间:2024/04/28 18:40

先了解一下null:

null既不是对象也不是一种类型,它仅是一种特殊的值,你可以将其赋予任何引用类型,你也可以将null转化成任何类型,如:

String str = null;// null can be assigned to String
Integer itr = null;// you can assign null to Integer also
Double dbl = null// null can also be assigned to Double
 
String myStr = (String) null;// null can be type cast to String
Integer myItr = (Integer) null;// it can also be type casted to Integer
Double myDbl = (Double) null;// yes it's possible, no error

进入正题:

下面的代码,通过为null的引用调用静态方法,且并未产生异常。

public class Why {  public static void test() {    System.out.println("Passed");  }  public static void main(String[] args) {    Why NULL = null;    NULL.test();  }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

test() 是一个静态方法,调用静态方法不需要创建实例对象。静态成员应该通过类型来访问,上面对test()方法通常应该写为Why.test();Java中可以通过对象引用表达式来访问一个静态成员,但这样通常会引起误解,因为这不是访问静态成员的常见形式。

hy aNull = null; aNull.test(); // 实际开发中不要这样写// 调用 Why.test(), 不会抛出 NullPointerException
  • 1
  • 2
  • 3

当通过一个对象引用访问静态成员时,访问只与所声明的引用类型相关。即: 
1. 所引用对象是否为null无关紧要,因为访问静态方法不需要实例对象。 
2. 如果引用不为null,运行时对象类型也无关紧要,因为静态调用不会导致动态调用分派。而是与类相关。

对于第2点的示例。

class T {    public static void p() {        System.out.println("p() in T");    }}class T1 extends T {    public static void p() {        System.out.println("p() in T1");    }}public class Main {    public static void main(String[] args) {        T t = new T1();        t.p();    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

最后访问静态方法,建议使用标准写法来写,这样不容易引起误解,也便于走读维护。

原文地址:http://stackoverflow.com/questions/3293353/how-come-invoking-a-static-method-on-a-null-reference-doesnt-throw-nullpointe

原创粉丝点击