java - 基于访问器方法强制执行严格继承

标签 java inheritance interface polymorphism abstract-class

假设基类定义为,

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/

相关文章:

java - 继承中的协方差

Delphi:如何从接口(interface)类型变量访问对象的基类方法

java - 创建接口(interface)的 "object"

java - 如何序列化父类(super class)以及可序列化类的字段

java - 从字符串读取对象时出现 StreamCorruptedException

c++ - 没有数据成员的菱形(多重继承)

Ruby 从基类访问派生类 "class methods"

Java:接口(interface)可以包含其中定义的常量变量吗?

java - 使用循环打印 int 值中的字符,每行输出具有所需数量的数字

java - 描述 Adob​​e Premiere Pro 的工具或架构