Reputation: 7110
I have an interface like
public interface AnInterface {
Consumer<Object> getConsumer();
}
And an implementation class like
public class AClass implements AnInterface {
@Override
public Consumer<String> getConsumer() {
return System.out::println;
}
}
This (correctly) does not compile since Consumer<String>
does not extend Consumer<Object>
.
However, if I change the interface to have an extra, unused type parameter on getConsumer, the error goes away and it compiles fine:
<T> Consumer<Object> getConsumer();
What's going on here?!
This occurs with javac in JDK 1.8 u20 and the Eclipse compiler in Luna.
Upvotes: 2
Views: 119
Reputation: 62874
The reason the code compiles, when you add the type parameter <T>
, is that in this case you're overriding the raw getConsumer()
method, i.e. you are not re-defining a type parameter (<T>
), but you're just ignoring it.
It's worth mentioning that when extending raw classes or overriding raw methods, the whole generic information is just ignored, which means that in this case the compiler will not verify if the type parameter of the overriding method (<String>
) is compatible with the type-parameter of the abstract method (<Object>
).
If you had kept the method as generic, it would look like:
@Override
public <T> Consumer<String> getConsumer() {
...
}
and then the compiler would correct raise a compile-time error.
Upvotes: 3
Reputation: 5126
you should write like this:
public interface AnInterface<T> {
Consumer<T> getConsumer();
}
public class AClass implements AnInterface<String> {
@Override
public Consumer<String> getConsumer {
return System.out::println;
}
}
Upvotes: 0