gpt4 book ai didi

java - 在泛型中使用继承的有问题的声明

转载 作者:行者123 更新时间:2023-12-01 17:03:39 25 4
gpt4 key购买 nike

我有

LoginCommandExecutor implements CommandExecutor<LoginCommand>
LoginCommand implements Command

为什么这一行会抛出编译错误:

CommandExecutor<Command> a = new LoginCommandExecutor(commander, null);

但它适用于以下两种情况:

CommandExecutor<? extends Command> a = new LoginCommandExecutor(commander, null);
CommandExecutor b = new LoginCommandExecutor(commander, null);

如果两者都有效,哪一个更可取?为什么?

因为我看到 a 和 b 在 IDE 中显示了相同的方法

最佳答案

CommandExecutor b = new LoginCommandExecutor(commander, null);

使用原始类型。绝对不应该使用它。

CommandExecutor<? extends Command> a = new LoginCommandExecutor(commander, null);

是正确的,但隐藏了一个事实,即您拥有的实际上是 CommandExecutor<LoginCommand> 。您将无法向该执行器提交任何命令,因为执行器接受的命令类型未知。

CommandExecutor<Command> a = new LoginCommandExecutor(commander, null);

是错误的,因为 LoginCommandExecutor 只接受 LoginCommand,而 CommandExecutor<Command>接受任何类型的命令。如果编译器接受了,你可以这样做

CommandExecutor<Command> a = new LoginCommandExecutor(commander, null);
a.submit(new WhateverCommand());

关于java - 在泛型中使用继承的有问题的声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26481029/

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