java - 如何正确限制泛型接口以扩展 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));
}
解决方案
这是编译器实际上试图通过发出有关使用原始类型的警告来帮助您的地方:如果您将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));
这就是为什么您应该始终避免使用原始类型的原因,编译器可以推断出正确的类型绑定。
现在我们有了编译错误消息,我们知道问题出在哪里:参数10
和5
是int
值,而接口Computable
需要Float
值,因此您可以将它们修复为浮点值:
System.out.println("The result is: " + compIn.compute(10f, 5f));
推荐阅读
- python - 来自 unix 管道的 pip install 参数
- python - Django:让用户从数据库下载 PDF 文件
- c - 使用 snd_pcm_writei() 播放音频时如何正确处理 ALSA 编程中的 xrun?
- excel - range() 之前的点是什么意思?
- azure - 从 Azure DevOps 创建应用注册的 Azure CLI - 权限不足
- sql - 您可以在 SQL 数据库拉取中使用 excel 查找表吗?
- asp.net - 尝试访问父表的外键时出现 NullReferenceException
- ms-access-2010 - 如何使用自定义格式删除 %
- visual-studio - RDLC 报表设计器 VSIX 文件不会安装
- rubocop - 为什么这个发送模式不匹配?