我有
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/