Search code examples
javainheritancesubtyping

Dynamic constructor calling in java?


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?


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