Implementing Abstract Generic Method in Java with multiple generics types
For completion to JB Nizet's answer, when you write:
<K>
It implicitly means:
<K extends Object>
That method must accept any object. Limiting it to DesiredClass
on a subclass effectively overwrites nothing, like the error message says.
overridden methods must have the exact same signature, no sub/super types allowed neither in parameters or return types.
Edit: Actually as discussed in the comments, String public foo();
effectively overrides Object public foo();
.
public abstract <T,K> T get (K entity);
is a method that can take anything as argument, and is allowed to return anything.
Overriding it with
public Integer get (DesiredClass entity)
doesn't work, since you restrict the types of argument that can be passed to the method to DesiredClass, and thus break the Liskov principle.
It would be easier to understand without generics. Suppose you have an abstract method in class Bar:
public abstract void fillRecipient(Recipient r);
and you try to override in SubBar it with
public void fillRecipient(Glass glass) {
}
What would the following code do if the above was legal?
Bar bar = new SubBar();
bar.fillRecipient(new Mug());