为什么我可以将课程设置为null并之后仍然从中调用方法?

发布于 2025-02-04 00:54:28 字数 1163 浏览 1 评论 0原文

我在Java中创建了以下示例代码:

public class SetClassNullExperiment {

    public static void main(String[] args) {
        SetMeNull c1 = new SetMeNull();
        c1.setInputToNull(c1);
        System.out.println("Is c1 equal to null? " + Boolean.toString(c1 == null)); // false
        c1.printHelloWorld();

        SetMeNull c2 = new SetMeNull();
        c2 = null;
        System.out.println("Is c2 equal to null? " + Boolean.toString(c2 == null)); // true
        c2.printHelloWorld(); // Throws a NullPointerException (For obvious reasons...)
    }

}

class SetMeNull {

    /**
     * Set the input class equal to <code>null</code>.
     */
    public void setInputToNull(SetMeNull c) {
        c = null;
    }

    public void printHelloWorld() {
        System.out.println("Hello World!");
    }

}

为什么在C1.C1.SetInputtonull(C1)之后可以调用c1.printhellowerld()?我希望在调用c1.printhellowerld()nullpoInterException。为什么不是这样?我认为,前四行(c1)等于最后四行(c2),但仅在最后四行a nullpointerexception 被抛出。

I have created the following example code in Java:

public class SetClassNullExperiment {

    public static void main(String[] args) {
        SetMeNull c1 = new SetMeNull();
        c1.setInputToNull(c1);
        System.out.println("Is c1 equal to null? " + Boolean.toString(c1 == null)); // false
        c1.printHelloWorld();

        SetMeNull c2 = new SetMeNull();
        c2 = null;
        System.out.println("Is c2 equal to null? " + Boolean.toString(c2 == null)); // true
        c2.printHelloWorld(); // Throws a NullPointerException (For obvious reasons...)
    }

}

class SetMeNull {

    /**
     * Set the input class equal to <code>null</code>.
     */
    public void setInputToNull(SetMeNull c) {
        c = null;
    }

    public void printHelloWorld() {
        System.out.println("Hello World!");
    }

}

Why is it possible to call c1.printHelloWorld() after c1.setInputToNull(c1) has been called? I would expect a NullPointerException when calling c1.printHelloWorld(). Why is this not the case? In my opinion, the first four lines (c1) are equal to the last four lines (c2), but only in the last four lines a NullPointerException is thrown.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戏剧牡丹亭 2025-02-11 00:54:28

这两个示例并不相同。在第一个中,您将引用的副本设置为null(请参见,例如,例如 - by-reference-or-pass-by-value.html“ rel =“ nofollow noreferrer”> this )。如果要在c内调用该方法setInputtonull,则将其在那里获取NPE。

The two examples aren't the same. In the first, you're setting a copy of the reference to null (see, e.g. this). If you were to call the method on c inside setInputToNull, you'd get the NPE there.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文