我有一个对象A,在实例化之后,我对其状态进行各种操作。在 的方法中A,我需要创建B另一个类的多个实例(调用它们)。对象类在B很大程度上依赖于 的状态A,而实例可以影响A的状态。
问题如下。由于已经实例化并且在调用其中需要任何实例化A的方法之前对其状态进行了操作,因此如果我不想在其中调用(因为已经实例化) ,我该如何使用继承来编写类?ABBsuper()BA
我必须在这里将B' 类与A' 类结合起来吗?
public class Test {
public static void main(String[] args) {
ClassA instanceA = new ClassA(5000000L); //Initial instantiation and state-setting operation to A.
instanceA.update(); //Try to get A to create B, where B relies on A's new state from previous operations.
}
}
class ClassA {
long tempLong;
ClassB instanceB;
public ClassA(long setLong) {
tempLong = setLong;
}
public void update() {
this.instanceB = new ClassB(); //instanceA needs an instanceB to work with.
}
}
class ClassB extends ClassA {
long tempLong2;
public ClassB() {
// I don't want to call super() here because instanceA is already created and instanceA's state is already set!;
this.tempLong2 = super.tempLong*2; //instaceA's state is necessary for instanceB to function!
}
}