我想声明一个超类的数据成员,私营:访问私有数据成员
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;
}
}
正如你所看到的,我这里有一个问题:超不能访问verySensitive,因为它是私人的,但我不想做出非常敏感的保护,因为它非常敏感。
另请注意,setVerySensitive是抽象的,因为检查有效值只能在超类构造完成后才能完成。
你能推荐一种摆脱这种“捕捉22”情况的优雅方式吗?
这不就是语言的_feature_?你只是选择设置为受保护的,如果它需要继承 – 2011-03-31 19:42:48
@Greg Flynn你是对的,在C++中这不是问题,因为受保护的数据成员可以被子类访问,但仍然对类的用户隐藏。在Java中,protected使它可用于整个包,而不仅仅是超类。 – 2011-03-31 20:00:40