为什么我可以将课程设置为null并之后仍然从中调用方法?
我在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这两个示例并不相同。在第一个中,您将引用的副本设置为
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 onc
insidesetInputToNull
, you'd get the NPE there.