假设我们有以下类(class):
interface Event {
}
@FunctionalInterface
interface EventListener<T extends Event> {
void onEvent(T event);
}
class Service {
class ServiceEvent implements Event {
}
public void onServiceEvent(ServiceEvent event) {
}
}
为什么编译以下赋值没有任何问题:
Service service = new Service();
EventListener<ServiceEvent> listener = service::onServiceEvent;
但是这个:
Service service = new Service();
EventListener<? extends Event> anotherListener = service::onServiceEvent;
失败,出现以下编译错误:
Error: java: incompatible types: invalid method reference incompatible types: Event cannot be converted to Service.ServiceEvent
最佳答案
public void onServiceEvent(ServiceEvent event) {}
这仅接受
ServiceEvent
参数。就像:EventListener<ServiceEvent> listener = service::onServiceEvent;
但:
EventListener<? extends Event> anotherListener
不仅可以接受
ServiceEvent
,还可以接受Event
类型的所有子类型。因此,类型不匹配