英文:
Initializing instance of a class as null
问题
为什么会是这样?
代码:
public class Class1 {
Class1 c1;
public Class1() { c1 = null; }
}
public class Class2 {
public static void main(String[] args) {
Class1 cs1 = new Class1();
System.out.println(cs1 == null);
}
}
在 Class1
中,我在构造函数中将 c1
初始化为 null
。然后在 Class2
中实例化了 Class1
,然后检查它的值是否真的为 null
(cs1 == null
),输出结果是 false
。为什么会输出 false
?cs1
是 null
,因此应该打印为 true
。为什么会发生这种情况?有人能解释一下吗?谢谢...
英文:
Why is it like this?
Codes:
public class Class1 {
Class1 c1
public Class1() { c1 = null; }
}
public class Class2 {
public static void main(String[] args) {
Class1 cs1 = new Class1();
System.out.println(cs1 == null);
}
}
In Class1
I initialized the c1
as null
in its contructor. Then
when I instantiated the Class1
in Class2
then check if its value is really null (cs1 == null)
the output it produces is false
.
Why does it output as false
? cs1
is null
, hence it's supposed to print as true
. Why does this happen? Can someone please explain this to me? Thanks...
答案1
得分: 1
你确实将 c1
初始化为 null 了,但是在构造函数中正在初始化的不是 c1
,而是 Class1
。
new Anything()
永远不会是 null。
英文:
You did initialize c1
as null, yes, but c1
is not the Class1
being initialized in the constructor.
new Anything()
is never, ever null.
答案2
得分: 0
Class1
的c1
属性为null,而不是实例本身。所以,基本上你创建了一个围绕着null的包装器。这将打印出true
:
System.out.println(cs1.c1 == null);
英文:
Class1
‘s c1
attribute is null, not the instance itself. So, basically you’ve created a wrapper around a null. This should print true
:
System.out.println(cs1.c1 == null);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论