初始化一个类的实例为空值

huangapple go评论72阅读模式
英文:

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,然后检查它的值是否真的为 nullcs1 == null),输出结果是 false。为什么会输出 falsecs1null,因此应该打印为 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

Class1c1属性为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);

huangapple
  • 本文由 发表于 2020年9月22日 23:42:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/64013189.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定