【发布时间】:2016-03-20 21:11:45
【问题描述】:
过去几天我一直在努力解决这个问题,并搜索了我能想到的一切都无济于事。
我有一个类通过接口与另一个类交互。我遇到了一些类型不匹配错误,代码对我来说似乎很简单。
public class FooBar {
Foo<? extends Bar> X = new Y();
public void test(){
if X.isA(X.B()){
//do something; type mismatch here
}
}
}
界面:
public interface Foo<T extends Bar> {
public T B();
public boolean isA(T t);
}
实施:
public class Y implements Foo<T extends Bar> {
public int B(){
return 5;
}
public boolean isA(int num){
int A = 10;
return (A == num) ? true : false;
}
我的问题是 test() 方法。我通过接口获取一个数字,然后用相同的实现类实例对其进行测试,但这给了我一个捕获/类型不匹配错误。
CAP#1 从 ? 的捕获扩展 Bar扩展栏
CAP#2 从捕获的 ? 扩展 Bar扩展栏
我尝试了很多在搜索中找到的东西,但没有一个奏效。泛型和接口对我来说是新的,我还在学习它们。提前感谢您的帮助!
【问题讨论】:
-
不应该
isA使用T而不是int吗?或者类的签名改为public class Y implements Foo<Integer> -
作为旁注
return (A == num) ? true : false;可能只是return A == num; -
Bar 类在哪里?
-
您的
X是一个消费者,所以它应该是Foo<? super Bar>,如果甚至需要通配符的话。 stackoverflow.com/q/2723397/2891664 -
一个不正确的项目是你有一个接口
Foo<T extends Bar>。然后你有具体的类Y implements Foo<T extends Bar>对于 Y,'T' 是 int 类型,这是无效的。 “T”不能是基元,必须是扩展 Bar 的类。