使属性可读/可写但不可覆盖/可重新声明?

时间:2017-10-08 21:15:19

标签: java

是否可以阻止子类覆盖/重新声明类属性,但仍然让它们读取它&写吧?

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

1 个答案:

答案 0 :(得分:1)

将其设为私有并提供访问者。

class Human
{
    private boolean isMale;

    public boolean isMale() {
        return isMale;
    }

    public void setIsMale(boolean isMale) {
        this.isMale = isMale;
    }
}

请注意,您无法避免重新声明。