为什么我没有得到NullPointerException? [英] Why I am not getting NullPointerException?

查看:170
本文介绍了为什么我没有得到NullPointerException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Java中空引用的静态字段

我理解静态方法是在类级别上。所以我知道我不需要创建实例来调用静态方法。但我也知道我可以调用静态方法LIKE一个实例方法。这是我感到困惑的地方,因为我在从null对象调用静态方法时(例如在调用实例方法中)期待 NullPointerException 。我真的很感激为什么我错在这里期待 NullPointerException 的一些解释。

I understand that static methods are on class level. So I am aware that I do not need to create instance to call static methods. But I am also aware that I can call static method LIKE an instance method. This is where I am confused, because I was expecting a NullPointerException while calling the static method from the null object (as in calling instance method). I would really appreciate some explanation on why I was wrong to expect a NullPointerException here.

以下是示例代码:

public class SampleClass {

    public static int getSumStatic(int x, int y){
        return x+y;
    }

    public int getDifferenceInstance(int x, int y){
        return x-y;
    }
}

public class TestClass {

    public static void main (String[] args){        
    SampleClass sc=null;

    System.out.println(SampleClass.getSumStatic(2, 2)); //as expected

    //I was expecting NullPointerException in the next line, since I am accessing null object
    System.out.println(sc.getSumStatic(4,5)); //static method , executes perfectly  

    System.out.println(sc.getDifferenceInstance(6,4));//throws NullPointerException
    }
}


推荐答案

通过实例调用静态方法不需要实例存在。只要编译器能够确定变量的类型,它在评估 sc 表达式并丢弃结果后静态地进行等效调用:

Calling a static method through an instance does not require the instance to be there. As long as the compiler is able to determine the type of the variable, it makes the equivalent call statically after evaluating the sc expression and discarding the result:

System.out.println(SampleClass.getSumStatic(4,5));

来自 Java语言规范


第15.12.1节

Section 15.12.1

❖如果表格是 Primary.NonWildTypeArgumentsopt Identifier ,则该方法的名称为
,即标识符。设T为主表达式的类型。如果T是类或接口类型,则要搜索的类或接口是T,如果T是类型变量,则是T的上限。

❖ If the form is Primary.NonWildTypeArgumentsopt Identifier, then the name of the method is the Identifier. Let T be the type of the Primary expression. The class or interface to be searched is T if T is a class or interface type, or the upper bound of T if T is a type variable.

第15.12.4.1节:

Section 15.12.4.1:


  1. 如果MethodInvocation的第二个产品(包括一个Primary)涉及
    ,则有两个子类:

❖如果调用模式是静态的,则没有目标引用。计算
表达式Primary,但结果将被丢弃。

❖ If the invocation mode is static, then there is no target reference. The expression Primary is evaluated, but the result is then discarded.

这篇关于为什么我没有得到NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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