Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling derived class method using base class object

Tags:

java

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?

figure

like image 903
Raj Avatar asked Mar 08 '13 17:03

Raj


2 Answers

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.

like image 126
wallenborn Avatar answered Oct 23 '22 23:10

wallenborn


you could always cast. suppose your class A provides this method:

protected B getBInstance() {
   return bObject;
}

then in A_Base1 you could do something like:

((B_Base1)getBInstance()).method2();

this, however, is a VERY bad design. if your A_Base1 class needs an instance of B_Base1 it should be handed such an instance directly at construction time:

public class A_Base1 extends A {
   private B_Base1 b1Object;
   public A_Base1(B_Base1 instance) {
      super(B_Base1); //works as a B for parent
      this.b1Ovject = instance;
   }
}

and then you can use that

like image 33
radai Avatar answered Oct 24 '22 00:10

radai