سؤال

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