3

Consider the following example,

class ClsA {}
class ClsB {}

interface IntA {}
interface IntB {}

And I have 2 very similar methods:

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;
}

And then the method calls:

ClsA ac = returnC(); // This works fine based on inference.

IntA ai = returnI(); // Similarly this works fine based on inference.

But consider the below 2:

ClsB bc = returnC(); // ERROR as expected.

Eclipse Error:

Bound mismatch: The generic method returnC() of type Testing is not applicable for the arguments (). The inferred type ClsB&ClsA is not a valid substitute for the bounded parameter <T extends ClsA>

But the following code compiles fine:

IntB bi = returnI(); // Works fine

Why is that for interface, the generics bound is not considered in return types?

4

1 回答 1

1

这里的神奇词汇是原始多重继承

让我们先看看你的returnC方法:

static <T extends ClsA> T returnC() {
    return null;
}

该类型T以 为界ClsA,这意味着如果您调用原始 returnC方法,则返回类型将为 simple ClsA

没错,当你有这样ClsA ac = returnC();的语句时:编译器编译成功,因为方法的原始返回类型是ClsA,它与 的类型兼容ac

原始返回类型也是该语句ClsB bc = returnC();无法编译的原因。


现在让我们看一下returnI方法:

static <T extends IntA> T returnI() { // Here T extends the interface
    return null;
}

在这里,类型参数只绑定到IntA

然而,这并不意味着替换类型 forT必须只实现IntA- 该类型可以IntA同时实现IntB。like 语句IntB bi = returnI();是允许的,因为一个类型可以实现多个接口,但不能实现多个类。

考虑这个类:

class SomethingReallyCool implements IntA, IntB { }

此类型是type-parameter 的有效替代品,returnI()其证明是以下语句:

IntB bi = YourClass.<SomethingReallyCool>returnI();

为什么?因为它是一个实现的类,IntA这是编译器唯一关心的事情。

于 2015-12-03T12:01:41.730 回答