【发布时间】:2020-04-28 16:58:48
【问题描述】:
我想将子类继承的属性初始化为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;}}
我使用另一个类的另一个对象将参数传递给插入方法。子类中的构造函数初始化条件:
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;
有没有办法将继承属性更改为最终属性?如果传递了符合条件的东西并且继承的方法会尝试更改属性,是否会出现异常?
【问题讨论】:
-
为什么要这样做?这似乎是一个 XY 问题。无论如何,如果这是可能的,请考虑如果您将变量更改为
final但随后调用了更改它的超类方法会发生什么。 -
我可以在插入方法中检查一个属性是否是最终的,例如:
if(s == attribute && (s != final) {this.attribute = true;},但以一种可行的方式?我正在创建一个在某些子类中需要 immutable 属性的项目,但我想在超类中包含 insert methid -
这是XY problem。
-
我已经重写了底部的问题。我不担心这是一个 XY 问题。我只介绍了思路。如果我没有写任何东西来澄清我的问题,那可能会被误解。
标签: java inheritance constructor attributes final