문제

Assume I have 4 classes: A, B, SA and SB where B extends A and SB extends SA.

Class A has the following constructor:

private SA a;
public A() {
   a = new SA();
}

Obviously when I'm calling the contructor for class B and since B extends A constructor of class A is also called. But in such a case I would like the constructor of A to do a = new SB(); instead of a = new SA();.

Is there an easy way to do this without changing the public interfaces of both A and B?

도움이 되었습니까?

해결책

Just have a public constructor and a protected constructor:

private SA a;
public A() {
   this(new SA());
}
protected A(final SA a) {
   this.a = a;
}

Then in B:

public B() {
   super(new SB());
}

다른 팁

Yes it is. For example :

public A(YourEnum en) {
    if (en == YourEnum.SA){
        a = new SA();
    } else {
        a = new SB();
    }
}

Also, depends on what you really need, it can be done by overloading constructors

public A(){
    a = new SA();
}

public A(YourObjectYouNeed dataNeededForAnotherConstructor){
    //doing initialization stuff
    a = new SB();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top