calling derived class method using base class object

java

Solution

Using inheritance like this imo only makes sense if the Bx.methodX() do something that means she same to the different Ax. And in that case, you should name them that way:

public class B {
  public void doWhatAMeans() {
    method1();
  }

public class B1 extends B {
  @Override
  public void doWhatAMeans() {
    method2();
  }

public class B2 extends B {
  @Override
  public void doWhatAMeans() {
    method3();
  }

and then you only need A to call doWhatAMeans() and the A1 and A2 only need to be injected the appopriate instances of Bx.

On the other hand, if doWhatAMeans does not make sense because the methodX do different things that mean different things to Ax, then you need to rethink your object model, probably the parallel structures A,A1,A2 and B,B1,B2 are wrong then.

Problem

I have 6 classes as shown in figure below. Now, `class A` has an object of class `B` as a private variable defined. Also class `A` methods calls many methods from class B, for example `B.method1()`. Now, class `A_Base1` is which is derived from class `A`, needs to call methods from the derived class `B_Base1`; for example `B1.method2()`. And also methods of class `A_Base2` needs to call methods from class `B_Base2`; for example `B2.method3()`. Now in class A I define the variable as - `private B bObject` Now in method of `A_Base1`, I cannot cannot call the methods like `bObject.method2()` since its a base class object. I need suggestions on - Is it possible to call derived class object methods using base class object? Or do I need to re-design this scenario in some other good way?

Original source