当主实例为空时,实例中的实例是否会为空
Will instances inside an instance get null'ed when the main instance is null'ed
假设我们有这段代码:
public class c1 {
c2 secondclass = new c2();
}
public class c2 {
public c2() {
System.out.println("c2 instance created");
}
}
如果我设置 c1 = null
,c1
中的 class c2
会自动清空吗?
或者我需要:
c1.c2 = null;
c1 = null;
不,不会。重要的是要了解您永远不会将 instance 设置为 null - 您只需将 variable 的值设置为 null。可以有多个变量引用同一个实例。很难对您的确切示例发表评论,因为您似乎使用 class 名称作为变量名称,但如果您有:
public class Foo {
// Note that good code almost never has public fields; this is for demo purposes only
public Bar bar;
}
public class Bar {
@Override public String toString() {
return "Message";
}
}
然后你可以这样做:
Foo foo1 = new Foo();
Foo foo2 = foo1;
// The values of foo1 and foo2 are now the same: they are references to the same object
foo1.bar = new Bar();
System.out.println(foo2.bar); // Prints Message
foo2 = null;
System.out.println(foo2); // Prints null
System.out.println(foo1.bar); // Still prints Message
将 foo2
的值更改为 null 会使 no 与 foo1
不同 - 它不会更改 foo1
的值, foo1
的值所指的对象也没有任何区别。
一般来说,您需要非常非常清楚 the differences between objects, variables and references。一旦你弄清了这种心智模型,很多其他事情就会变得更容易理解。
假设我们有这段代码:
public class c1 {
c2 secondclass = new c2();
}
public class c2 {
public c2() {
System.out.println("c2 instance created");
}
}
如果我设置 c1 = null
,c1
中的 class c2
会自动清空吗?
或者我需要:
c1.c2 = null;
c1 = null;
不,不会。重要的是要了解您永远不会将 instance 设置为 null - 您只需将 variable 的值设置为 null。可以有多个变量引用同一个实例。很难对您的确切示例发表评论,因为您似乎使用 class 名称作为变量名称,但如果您有:
public class Foo {
// Note that good code almost never has public fields; this is for demo purposes only
public Bar bar;
}
public class Bar {
@Override public String toString() {
return "Message";
}
}
然后你可以这样做:
Foo foo1 = new Foo();
Foo foo2 = foo1;
// The values of foo1 and foo2 are now the same: they are references to the same object
foo1.bar = new Bar();
System.out.println(foo2.bar); // Prints Message
foo2 = null;
System.out.println(foo2); // Prints null
System.out.println(foo1.bar); // Still prints Message
将 foo2
的值更改为 null 会使 no 与 foo1
不同 - 它不会更改 foo1
的值, foo1
的值所指的对象也没有任何区别。
一般来说,您需要非常非常清楚 the differences between objects, variables and references。一旦你弄清了这种心智模型,很多其他事情就会变得更容易理解。