首页 > 解决方案 > 如何正确限制泛型接口以扩展 Java 中的 Number 类并能够在另一个类中运行它?

问题描述

我试图了解如何扩展接口并在另一个类中使用它,但每次编译器都会抛出转换错误。我曾尝试在 printResult 方法中使用通配符,但它不起作用。这里可能是什么问题?它仅适用于整数。

public interface Computable <T extends Number>
{
    public T compute(T x, T y);    
}

------------------------------------------------------------

public class TestComputable
{
    public static void main(String[] args)
    {
        Computable<Float> comp;
        comp = (x, y) -> x + y;
        printResult(comp);
    }
}

public static void printResult(Computable compIn)
{
    System.out.println("The result is: " + compIn.compute(10, 5));
}

标签: javagenericsinterfaceextendssubtyping

解决方案


这是编译器实际上试图通过发出有关使用原始类型的警告来帮助您的地方:如果您将printResult方法更改为使用正确的类型参数,如下所示:

public static void printResult(Computable<Float> compIn) { // instead of Computable compIn

那么编译器会在编译时显示错误:

// Now the compiler throws error:
// the method compute(Float, Float) is not applicable for the arguments (int, int)
System.out.println("The result is: " + compIn.compute(10, 5));

这就是为什么您应该始终避免使用原始类型的原因,编译器可以推断出正确的类型绑定。

现在我们有了编译错误消息,我们知道问题出在哪里:参数105int值,而接口Computable需要Float值,因此您可以将它们修复为浮点值:

System.out.println("The result is: " + compIn.compute(10f, 5f));

推荐阅读