gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:35:59 27 4
gpt4 key购买 nike

我想声明一个父类(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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com