我有一个抽象父类(super class) ValueType
和两个非抽象子类 IntType
和 DoubleType
.如何在父类(super class)方法中定义类型,如下所示
public abstract class ValueType {
public abstract <T extends ValueType> T add(T other);
}
我允许在子类方法中编写具体类型(例如
public IntType add(IntType other)
或 DoubleType add(DoubleType other)
)public class IntType extends ValueType {
private int val;
public IntType(int val){
this.val = val;
}
public int getVal(){
return this.val;
}
@Override
public IntType add(IntType other) {
return new IntType(this.val + other.getVal());
}
public class DoubleType extends ValueType {
private double val;
public DoubleType(double val){
this.val = val;
}
public double getVal(){
return this.val;
}
@Override
public DoubleType add(DoubleType other) {
return new DoubleType(this.val + other.getVal());
}
在上面的例子中,子类方法不会覆盖父类(super class)方法。
最佳答案
使抽象类本身通用,而不仅仅是它的方法。
提升泛型 <T extends ValueType>
作为类泛型参数。注意这个 Action 类 ValueType
也变得通用,因此 <T extends ValueType<T>>
代替原始类型:
public abstract class ValueType<T extends ValueType<T>> {
public abstract T add(T other);
}
然后具体的子类从泛型类扩展,并被迫重写抽象方法(私有(private)字段、getter 和 setter 被省略):
public class IntType extends ValueType<IntType> {
@Override
public IntType add(IntType other) {
return new IntType(this.val + other.getVal());
}
}
public class DoubleType extends ValueType<DoubleType> {
@Override
public DoubleType add(DoubleType other) {
return new DoubleType(this.val + other.getVal());
}
}
顺便说一句,你有两个错别字:
return new IntType(this.value + other.getVal());
应该使用 this.val
. return new DoubleType(this.value + other.getVal());
应该使用 this.val
也是。 关于java - 子类中参数化父类(super class)方法和非参数化(具体类型)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61735000/