考虑下面的例子,
class ClsA {}
class ClsB {}
interface IntA {}
interface IntB {}我有两种非常相似的方法:
static <T extends ClsA> T returnC() { // Here T extends the class
return null;
}
static <T extends IntA> T returnI() { // Here T extends the interface
return null;
}然后,该方法调用:
ClsA ac = returnC(); // This works fine based on inference.
IntA ai = returnI(); // Similarly this works fine based on inference.但请考虑以下2点:
ClsB bc = returnC(); // ERROR as expected.Eclipse错误:
绑定不匹配:类型测试的泛型方法returnC()不适用于参数()。推断类型ClsB&ClsA不能有效地替代有界参数
<T extends ClsA>。
但是下面的代码编译得很好:
IntB bi = returnI(); // Works fine为什么在接口中,在返回类型中不考虑泛型绑定?
发布于 2015-12-03 12:01:41
这里的神奇词汇是、raws、和多重继承。
让我们首先看看您的returnC方法:
static <T extends ClsA> T returnC() {
return null;
}类型T与ClsA绑定,这意味着如果调用原始 returnC方法,则返回类型将简单地为ClsA。
如果您有以下语句:ClsA ac = returnC();编译器成功编译,因为方法的原始返回类型是ClsA,它与ac类型兼容。
原始返回类型也是ClsB bc = returnC();语句不编译的原因。
现在让我们来看看returnI方法:
static <T extends IntA> T returnI() { // Here T extends the interface
return null;
}在这里,类型参数仅绑定到IntA。
然而,这并不意味着T的替换类型必须只实现IntA --可以同时实现IntA和IntB。允许像IntB bi = returnI();这样的语句,因为类型可以实现多个接口,但不能实现多个类。
考虑一下这门课:
class SomethingReallyCool implements IntA, IntB { }此类型是有效的替代returnI()的类型参数,并证明如下:
IntB bi = YourClass.<SomethingReallyCool>returnI();为什么?因为它是一个实现IntA的类,这是编译器唯一关心的事情。
https://stackoverflow.com/questions/34065038
复制相似问题