gpt4 book ai didi

java - PECS 不适用于具有接口(interface)的返回类型

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:56:28 24 4
gpt4 key购买 nike

考虑下面的例子,

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 错误:

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>

但是下面的代码可以正常编译:

IntB bi = returnI(); // Works fine

为什么对于接口(interface),返回类型中不考虑泛型绑定(bind)?

最佳答案

这里的魔法词是rawsmultiple inheritance

首先让我们看一下您的returnC 方法:

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

类型TClsA 绑定(bind),这意味着如果您调用raw returnC 方法,那么返回类型将只是ClsA

是的,当你有这个语句时:ClsA ac = returnC(); 编译器编译成功,因为方法的raw返回类型是ClsA,与ac类型兼容。

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


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

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

这里,类型参数只绑定(bind)到IntA

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

考虑这个类:

class SomethingReallyCool implements IntA, IntB { }

此类型是 returnI() 的类型参数的有效替代品,其证明如下:

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

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

关于java - PECS 不适用于具有接口(interface)的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34065038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com