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

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

问题描述

可能的重复:
Java 中空引用上的静态字段

我知道静态方法是在类级别上的.所以我知道我不需要创建实例来调用静态方法.但我也知道我可以像实例方法一样调用静态方法.这就是我感到困惑的地方,因为在从 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 为 Primary 表达式的类型.如果 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天全站免登陆