为什么这段代码不会抛出NullPointerException [英] why doesn't this code throw NullPointerException

查看:100
本文介绍了为什么这段代码不会抛出NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚与我的朋友讨论了使用类名调用静态方法,并试用了这段代码并期望它在运行时抛出NPE。但结果却是dint。我只想了解执行顺序。

I was just discussing about calling static methods using class name with my friend and tried out this code and expected it to throw NPE at runtime.but as it turn out it dint. i just want to understand the execution order.

public class One {

    public static void method() {
        System.out.println("in static one");
    }
}

public class Two {

    static One o;

    public static void main(String[] args) {
        o.method(); // expected NPE here, as o is null
    }
}

我知道静态方法应该用它们的类名调用,我甚至知道当我们用实例调用静态方法时IDE会给出编译器警告。但我们也可以通过创建一个实例来调用它们,但是,我从来没有在这里创建过实例, o 应该得到它的默认值null,因此调用 o .method()应该在运行时抛出一个NPE,但事实并非如此。你们能不能对这段代码中的执行顺序有所了解。

I know that static methods should be invoked with their class name, I even know that IDE's would give a compiler warning when we call static methods with an instance. but we could also call them by creating an instance, however, i never created an instance here, o should get its default value null, thus calling o.method() should throw an NPE at run time, but it doesn't. can you guys please shed some light on how the execution order is in this code.

推荐答案

这很有用,因为重要的是编译时类型 > o 字段。编译器将 o.method()编译为与 One.method()相同的字节代码。

It works because what matters is the compile-time type of the o field. The compiler will compile o.method() into the same byte code as One.method().

特别是,如果你有一个两个的类一个 ,并且都声明静态void方法(),然后

In particular, if you had a class Two that extends One, and both declare a static void method(), then

One x = new Two();
x.method(); // calls One.method(), not Two.method()

适合混淆,少于有利于可维护性......

Good for obfuscation purposes, less good for maintainability...

这篇关于为什么这段代码不会抛出NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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