Ela*_*nda 0 java generics inheritance interface
我有
LoginCommandExecutor implements CommandExecutor<LoginCommand>
LoginCommand implements Command
Run Code Online (Sandbox Code Playgroud)
为什么这一行会引发编译错误:
CommandExecutor<Command> a = new LoginCommandExecutor(commander, null);
Run Code Online (Sandbox Code Playgroud)
但它适用于以下两个方面:
CommandExecutor<? extends Command> a = new LoginCommandExecutor(commander, null);
CommandExecutor b = new LoginCommandExecutor(commander, null);
Run Code Online (Sandbox Code Playgroud)
如果两者都有效,哪一个更好?为什么?
因为我看到a和b在IDE中显示相同的方法
CommandExecutor b = new LoginCommandExecutor(commander, null);
Run Code Online (Sandbox Code Playgroud)
使用原始类型.绝对不应该使用它.
CommandExecutor<? extends Command> a = new LoginCommandExecutor(commander, null);
Run Code Online (Sandbox Code Playgroud)
是正确的,但隐藏的事实是你拥有的实际上是一个CommandExecutor<LoginCommand>.您将无法向此执行程序提交任何命令,因为执行程序接受的命令类型未知.
CommandExecutor<Command> a = new LoginCommandExecutor(commander, null);
Run Code Online (Sandbox Code Playgroud)
是错误的,因为LoginCommandExecutor只接受LoginCommand,而CommandExecutor<Command>接受任何类型的命令.如果编译器接受了它,那么你可以这样做
CommandExecutor<Command> a = new LoginCommandExecutor(commander, null);
a.submit(new WhateverCommand());
Run Code Online (Sandbox Code Playgroud)