public class TestA {
public TestA() {
try {
for (int i = 0 ; i < 10000 ; i++){
Thread.sleep(1);
System.out.println("TestA生成中");
}
}catch (InterruptedException ex){
}
}
}
public class TestB {
private TestA a;
public TestB(TestA a) {
this.a = a;
}
public void refresh() {
a = new TestA();
}
public static void main(String[] args) {
TestB b = new TestB(new TestA());
b.refresh();
}
}
这个main方法中b的a会不会有一刻为null
这个refrush方法是先new好TestA 再把引用给a 还是有引用后就会给a 造成new TestA里面的东西没有打印完 a的引用就更改了 求解答
两个问题 求解答
第一个问题,在this.a = a;之前为null;
第二个问题,先new好TestA 再把引用给a,也不会没打印完就更改的,
TestB b = new TestB(new TestA());
//上下两种代码效果是等同的
TestA a = new TestA();
TestB b = new TestB(a);
new一个对象时会自动调用该类的构造函数,构造函数未执行完,该对象不会被创建;
也就是说TestA被传递到TestB的构造函数中时,TestA必然已经被创建,则TestA构造函数内的代码也一定被执行完完毕。