Search code examples
javainheritanceprivateabstract

Define identical treatment of private subclass members in superclass


I've got this parent class:

abstract class Parent {
  abstract int getX();
}

And two different subclass implementations:

class AgnosticChild extends Parent {

  private int x = 5;

  @Override
  int getX() {
    return x;
  }
}

class ManipulativeChild extends Parent {

  private static int x = 5;

  ManipulativeChild() {
    x++;
  }

  @Override
  int getX() {
    return x;
  }
}

Both getX() implementations are identical. Is there any way to get rid of this redundancy while keeping the different implementations for x? Assume that the getX() implementation is a lot more elaborate in practice.


Solution

  • No, the two implementations are not identical - one accesses a static field, and the other accesses an instance field. So although they look identical, they're functionally very different; and there's no opportunity for re-use here, without changing the behaviour of your classes.