java - 子类中参数化父类(super class)方法和非参数化(具体类型)方法

标签 java generics inheritance casting parameterized-types

我有一个抽象父类(super class) ValueType和两个非抽象子类 IntTypeDoubleType .如何在父类(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/

    相关文章:

    java - 找不到类 'android.graphics.drawable.RippleDrawable' Unicode 问题?

    java - Java中的可比实现

    scala - 在 Scala 中覆盖泛型特征的方法

    Ruby 模块和 Module#append_features 解释

    c++ - 成员访问和模板特化

    c++ - 交叉引用和循环依赖。 header 间接包含自身

    java - AtomicInteger 的多线程不起作用

    java - 重新启动 Roo 应用程序会刷新其对应的 MySQL 表

    Java EL 评估 bean 的属性

    java - 为什么编译器允许我将泛型集合分配给声明为类特定集合的变量?