JAVA:类型参数隐藏类类型

标签 java generics inheritance types covariance

我有这个

abstract class Operand {
    public abstract <T extends Operand> Operand operation(Operator operator, T operand);
}
abstract class Numeric extends Operand {
}
class Integer extends Numeric 
    @Override
    public <Integer> Operand operation(Operator operator, Integer operand) {//problem
    }
}

我该如何解决这种情况? 我不想在类 Operand 中使用泛型(所以我有 Operand),因为我需要 Operand 是单一类型。在 Integer 的方法内部,我需要调用构造函数(new Integer(arg)),解决方案可能是以其他方式调用该方法。 解决方案?

最佳答案

尝试使用重载方法

abstract class Operand {
    public abstract <T extends Operand> Operand operation(Operator operator, T operand);
}

abstract class Numeric<T extends Numeric<T>> extends Operand {
    public abstract Operand operation(Operator operator, T operand);
}

class Integer extends Numeric<Integer> {

    @Override
    public Operand operation(Operator operator, Integer operand) {
        // add your Integer specific code here
        return null; // replace null with actual returned value
    }

    @Override
    public <T extends Operand> Operand operation(Operator operator, T operand) {
        // simply call to overridden Integer specific method
        // no harm to downcast it here
        return operation(operator, (Integer) operand); 
    }

}

关于JAVA:类型参数隐藏类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23571861/

相关文章:

java - hibernate 中缺少@Temporal 注释

java - xpage添加文件下载控件时出现AbstractMethodError

c# - 为什么方法类型推断无法推断类型参数?

C++ 继承和成员访问问题

java - Groovy 中的 IDE,这可能吗?

java - 如何使用java为MySQL启用LDAP连接?

java - 泛型方法的泛型返回类型

c# - System.Reflection 与泛型——性能

c++ - 派生类中的函数重载

c++ - 有没有一种用额外的运算符扩展类的好方法?