Let's say we've got the following classes:
interface Event {
}
@FunctionalInterface
interface EventListener<T extends Event> {
void onEvent(T event);
}
class Service {
class ServiceEvent implements Event {
}
public void onServiceEvent(ServiceEvent event) {
}
}
Why does the following assignment compile without any problems:
Service service = new Service();
EventListener<ServiceEvent> listener = service::onServiceEvent;
but this one:
Service service = new Service();
EventListener<? extends Event> anotherListener = service::onServiceEvent;
fails with this compile error:
Error: java: incompatible types: invalid method reference incompatible types: Event cannot be converted to Service.ServiceEvent
答案 0 :(得分:1)
public void onServiceEvent(ServiceEvent event) {}
This accepts only ServiceEvent
parameters. Just like:
EventListener<ServiceEvent> listener = service::onServiceEvent;
but:
EventListener<? extends Event> anotherListener
Can accept not only ServiceEvent
but also all subtypes of the Event
type. Hence, the type mismatch