假设基类定义为,
abstract Base{
protected int field;
protected int getter(){
return this.field;
}
...
}
为了对子类型进行分类,在这个 getter 的基础上,我创建了一个类似的接口(interface),
interface MyFieldGettable{
public int getter();
}
我很高兴创建一个子类型,例如,
class CantGetField extends Base{
....
}
既然基本版本已经打印了该字段,那么让我们将补集子类型设置为,
class CanGetField extends Base implements MyFieldGettable {
public int getter(){
return this.getter();
}
}
现在,在一段代码中的某处有 List<Base>
,我想分离这两种类型,并检查 CanGetField
的字段类型。因此,我写道,
for(Base b:listOfBase){
if(b instanceof CanGetField){
int field = ((CanGetField)b).getter();
而且,如果你们现在已经猜到了。这会影响StackOverflowError
。现在,我可以通过更正类 CanGetField
的定义来解决这个问题。作为,
class CanGetField extends Base implements MyFieldGettable {
public int getter(){
return this.field;
}
}
或者,我可以更改接口(interface)中 getter 方法的名称,并将子类型中的所有调用委托(delegate)给基方法。但是,这将导致子类型中出现大量冗余代码。
还有其他解决办法吗?
最佳答案
This blows into StackOverflowError. Now, I can get around this by correcting the definition of class CanGetField as,
getter()
在这里进行无限递归调用:
class CanGetField extends Base implements MyFieldGettable {
public int getter(){
return this.getter();
}
}
如果您想重写 getter()
方法以仅更改修饰符而不更改其行为,则可以调用 super.getter()
:
class CanGetField extends Base implements MyFieldGettable {
public int getter(){
return super.getter(); // super implementation
}
}
关于java - 基于访问器方法强制执行严格继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44499144/