从子类访问私有数据成员

Reg*_*kie 1 java oop encapsulation visibility

我想声明一个超类私有的数据成员:

public abstract class superclass {
  private int verySensitive;

  abstract int setVerySensitive(int val); // must be overriden by subclass to work properly
}


public class subclass extends superclass {

  @Override
  protected int setVerySensitive(int val) {
    if (val > threshLow && val < threshHigh) // threshHigh is calculated in superclass constructor
       verySensitive = val;
  }
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我在这里有一个问题:超类不能访问verySensitive,因为它是私有的,但我不想让verySensitive受到保护,因为它是......敏感的.

另请注意,setVerySensitive是抽象的,因为只有在构造了超类之后才能检查有效值.

你能推荐一种优雅的方式摆脱这种"捕获22"的局面吗?

Ebo*_*ike 6

如何使检查抽象,但设置本身是私有的?

public abstract class superclass {
  private int verySensitive;

  abstract boolean verifySensitiveValue(int val); // must be overriden by subclass to work properly

  private void setVerySensitiveValue(int val) {
    if (verifySensitiveValue(val)) {
      verySensitive = val;
    }
  }
}


public class subclass extends superclass {

  @Override
  protected boolean verifySensitiveValue(int val) {
    return (val > threshLow && val < threshHigh); // threshHigh is calculated in superclass constructor
  }
}
Run Code Online (Sandbox Code Playgroud)


Ted*_*opp 5

我建议像这样:

public abstract class superclass {
  private int verySensitive;

  final int setVerySensitive(int val) {
    if (checkVerySensitive(val)) {
      verySensitive = val;
    }
  }
  protected abstract boolean checkVerySensitive(int val);
}


public class subclass extends superclass {

  @Override
  protected boolean checkVerySensitive(int val) {
    return val > threshLow && val < threshHigh; // threshHigh is calculated in superclass constructor
  }
}
Run Code Online (Sandbox Code Playgroud)

这类似于EboMike的建议,但它离开setVerySensitive(int)了包访问而不是私有.