Java – how to implement the same interface multiple times, but with different generics?
•
Java
There is already an answer to this question: > how to make a Java class that implements one interface with two generic types? six
public interface EventListener<T extends Event> { public void onEvent(T event); }
Now, I want to implement this interface in the following ways:
class Foo implements EventListener<LoginEvent>,EventListener<logoutEvent> { @Override public void onEvent(LoginEvent event) { } @Override public void onEvent(logoutEvent event) { } }
However, this gives me an error: copy class com foo. EventListener on line:
class Foo implements EventListener<LoginEvent>,EventListener<logoutEvent>
Can I implement the interface twice with different generics? If not, what can I do next to achieve what I do here?
Solution
You need to use internal or anonymous classes for example
class Foo { public EventListener<X> asXListener() { return new EventListener<X>() { // code here can refer to Foo } } public EventListener<Y> asYListener() { return new EventListener<Y>() { // code here can refer to Foo } } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码