是否可以阻止子类覆盖/重新声明类属性,但仍然让它们读取它&写吧?
class Human
{
public boolean isMale;
...
}
class Asian extends Human
{
public void livingLife()
{
// this is OK
(isMale) ? doSomething() : doSomethingElse();
// this is OK
isMale = false;
}
// redeclaration is not OK
public boolean isMale;
}
答案 0 :(得分:1)
将其设为私有并提供访问者。
class Human
{
private boolean isMale;
public boolean isMale() {
return isMale;
}
public void setIsMale(boolean isMale) {
this.isMale = isMale;
}
}
请注意,您无法避免重新声明。