0

我有一个对象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!
    }
}
4

1 回答 1

1

你的设计有一个根本性的缺陷。你似乎相信,当你打电话update()

public void update() {
    this.instanceB = new ClassB(); //instanceA needs an instanceB to work with. 
}

ClassB实例与this ClassA实例相关只是因为ClassB extends ClassA. 不,情况并非如此,因为new ClassB()创建了一个Object与.ClassAthis

如果唯一ClassB依赖于ClassAfor 的属性是 temprature 你最好将它传递给构造函数并在此处废弃继承(如果ClassBIS-NOT-A ClassA)。

public void update() {
    this.instanceB = new ClassB(this.tempLong);
}

public ClassB(long tempLong) {
    this.tempLong2 = tempLong * 2;
}

如果依赖项需要访问几乎所有ClassA属性,则通过将ClassA实例传递给ClassB.

public void update() {
    this.instanceB = new ClassB(this); // ClassA passes itself
}

public ClassB(ClassA classA) {
    this.classA = classA; // ClassB HAS-A ClassA relationship
    this.tempLong2 = classA.getTempLong() * 2;
}
于 2013-10-08T05:45:46.410 回答