Aquarius Power Aquarius Power - 2 months ago 10
Java Question

is there some trick to share methods behavior while using encapsulation?

I got this class structure:

abstract class A{
protected void doTest(){};
abstract void test();
}

abstract class B extends A{
}

class C extends B{
public void test(){
doTest();
}
}

class D extends A{
public void test(){
doTest();
}
}


D cannot extend B.

test() in both will implement the exact same functionality (that can contain several lines of code).

Currently I am being forced to copy the behavior identically.

I cannot create another class to implement the behavior because it access protected methods.

Is there any way out of this?

Answer

If test() truly is identical, it shouldn't be abstract.

abstract class A{
  protected void doTest(){};

  public void test() {
    //Shared functionality calling doTest() and doing other stuff. 
  }
}

Even if test() relies on fields in the various subclasses, you can make abstract getters and use those:

abstract class A{
  protected void doTest(){};

  protected abstract String getName();

  public void test() {
    //Shared functionality calling doTest() and doing other stuff. 
    //Can also use getName()
  }
}

abstract class B extends A {}

class C extends B {

    @Override public String getName() { return "C"; }

}

class D extends A {

    @Override public String getName() { return "D"; }

}
Comments