1
public class A {
    protected B mB;
    public A() {
        createB();
    }
    public void createB() {
        mB = new B();
    }
}

public class ChildA extends A {

    public ChildA() {
        super();
    }
    public void createB() {
        mB = new ChildB();
    }
}

public class B {
    public B() {
    }
}

public class ChildB extends B {
    public ChildB() {
    }
}

public class DemoApp {
    public static void main(String[] args) {
        A a = new ChildA();
    }
}

According to above code, we can see:

  1. when a A is newed, a B is created

  2. when a ChildA is newed, a ChildB is created.

My question is how can I inject mB in this polymorphism situation? If the design pattern is inappropriate,how can I refractor the code?

William Du
  • 11
  • 2

0 Answers0