Question

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?

Was it helpful?

Solution

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());
}

OTHER TIPS

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top