java - 从子类访问私有(private)数据成员

标签 java oop visibility encapsulation

我想声明一个父类(super class)的数据成员,私有(private)的:

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

如您所见,我这里有一个问题:父类(super class)无法访问 verySensitive,因为它是私有(private)的,但我不想让 verySensitive 受到保护,因为它...敏感。

另请注意,setVerySensitive 是抽象的,因为只有在构建父类(super class)后才能检查有效值。

您能推荐一种摆脱这种“第 22 条军规”情况的优雅方法吗?

最佳答案

将检查抽象化,但将设置本身设为私有(private)怎么样?

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

关于java - 从子类访问私有(private)数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5505322/

相关文章:

java - 如何将 String 转换为 at switch 语句的枚举?

c# - 理解 C# 中的基础

java - Java接口(interface)要求

oop - 默认情况下,私有(private)属性是否被 .perl 和 .gist 隐藏

javascript - 我不想使用 javascript 显示下拉值

javascript - 在同一空间中的两个 HTML 元素之间切换可见性

java - sql查询中的这个占位符是什么?

java - java.lang.Integer内部代码中的一个问题

java - 从 backbean JSF 更新 Javascript 源

CSS:解决 Chrome 中背面可见性错误的方法