在超类中定义对私有子类成员的相同处理

Define identical treatment of private subclass members in superclass

我有这个家长class:

abstract class Parent {
  abstract int getX();
}

以及两个不同的子class实现:

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;
  }
}

两个 getX() 实现是相同的。有没有办法在保留 x 的不同实现的同时摆脱这种冗余?假设 getX() 实施在实践中要复杂得多。

您可以将 int 变量拉到 Parent class 并在那里实现 getX 方法

abstract class Parent {
    private int x;

    public Parent(int x) {
        this.x = x;
    }

    public int getX() {
        return x;
    }

}

class AgnosticChild extends Parent {

    public AgnosticChild() {
        super(5);
    }


}

class ManipulativeChild extends Parent {


    ManipulativeChild() {
        super(6);
    }
}

更新: 如果您想将 ManipulativeChild 中的 x 声明为非静态字段,则上面的代码片段仅等于您的代码。否则,这是两个不同的实现,不能以建议的方式进行重构。

不,这两个实现并不相同——一个访问静态字段,另一个访问实例字段。因此,尽管它们看起来相同,但在功能上却大不相同;如果不改变 类.

的行为,就没有机会在这里重复使用