我想将子类继承的属性初始化为final。但是,当我访问该属性时,似乎是[[change,因此我想我已经创建了另一个最终属性。是否可以使超类中提到的属性成为最终属性而不创建另一个属性?
简化代码:public abstract Superobj {
protected boolean attribute = false;
protected String condition; //A condition to be checked in a subclass
protected String[] collection; //Stores strings
protected int howmany= 0;
public Superobj(int i){
this.collection = new String[i];}
public void insert(String s){
this.collection[howmany] = s;
howmany++;
if (s == condition) {attribute = true;}}
我使用另一个类的另一个对象将参数传递给insert方法。子类中的构造函数初始化条件:
public Subclass extends Superclass{ public Sublclass(int i){ super(i); this.condition = "cond";}}
但是,在一个子类中,无论插入到表中的什么内容,我都不想更改属性。例如,我想将其定为永久错误。我尝试过:
public FinalSubclass extends Superclass { protected final boolean condition = false; ...
但是,当我检查this.attribute的值时,它会根据传递的参数的值而变化-好像已经创建了另一个与继承的相反的this.attribute。我不能将类似的东西添加到子类的构造函数中:
final this.attribute = false;
有什么方法可以将继承的属性更改为final?如果有人传递了一些与条件匹配的东西,并且继承的方法将尝试更改属性,将会发生异常吗?
编译时错误。因此,您不能在runtime处“选择”变量为final
。但是,您似乎不需要这种功能。
[如果我了解您的使用权(我假设Superclass
是Superobj
的子类型),那么除了在attribute
中插入之外,您总是想在Superobj
(及其子类)中更改FinalSublcass
值) ]。因此,您可以通过以下方式仅覆盖insert
中的FinalSublcass
方法:
@Override
public void insert(String s){
this.collection[howmany] = s;
howmany++;
}
[如果您希望attribute
中的FinalSubclass
永不更改(不仅通过插入),可以在Superobj
中将字段设为私有,并创建protected setAttribute(String attribute)
设置器,该设置器应以某种方式在Subclass
中被覆盖:] >
@Override protected setAttribute(String attribute) { // do nothing or throw exception }
但是由于Liskov替代原则的违反(从我的角度来看,我不建议这样做)>>