2016-08-24 87 views

回答

5

这是因为您无法更改最终字段的值。

但是,如果你真的想本身它不同的值,你可以这样做:

class A { 
    protected final boolean b; 

    protected A() { 
    this(false); 
    } 
    protected A(boolean b) { 
     this. b = b; 
    } 
} 

class B extends A { 
    public B() { 
     super(true); 
    } 
} 
+1

我在说构造函数。 – stonar96

+0

@ stonar96当你调用超类的构造函数时,你设置了'b'的值。如果您想在子类中将其设置为不同的值,则需要将该值传递给超类构造函数。 – user902383

1

它不能这样做,因为final字段的定义是,它只能被分配一次。如果A()已经分配了保护字段,则在B()中再次分配它仍然违反“仅一次”,即使它在构造函数中完成。

相关问题