Elad Benda
Elad Benda

Reputation: 36656

Problematic declaration using inheritance in generics

I have

LoginCommandExecutor implements CommandExecutor<LoginCommand>
LoginCommand implements Command

Why this line throws compilation error:

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

But it works for both of followings:

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

And if both are working, which one is preferable? Why?

because I see a and b reveals same methods in the IDE

Upvotes: 0

Views: 36

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

CommandExecutor b = new LoginCommandExecutor(commander, null);

uses a raw type. It should definitely not be used.

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

is correct, but hides the fact that what you have is actually a CommandExecutor<LoginCommand>. You won't be able to submit any command to this executor, since the type of command accepted by the executor is unknown.

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

is wrong, since a LoginCommandExecutor only accepts LoginCommand, whereas CommandExecutor<Command> accepts any kind of Command. If that was accepted by the compiler, you could do

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

Upvotes: 5

Related Questions