Reputation: 1961
I am learning java generics, and trying to implement it for events before someone asks, i have considered using polymorphism, but since I want every event to send different values to the handler's start method, I can't do this.
This is my event handler:
public class MyHandler {
public void startEventAction(int num) {
//do something with num
}
}
This is my template event:
public abstract class SomeEvent<E> {
protected List<E> handler_list = new LinkedList<E>();
public SomeEvent() {
}
public Boolean addHandler(E handler) {
return handler_list.add(handler);
}
public Boolean removeHandler(E handler) {
return handler_list.remove(handler);
}
}
and the event itself is: (now i know it's probably wrong to extend the SomeEvent like this, but it seems to work)
public class MyEvent<MyHandler> extends SomeEvent<MyHandler> {
public void executeHandlers() {
for (MyHandler handler : handler_list) {
//Exception here!!
handler.startEventAction(num);
}
}
}
My question is how is it right to extend it and why does the function startEventAction doesn't exist for MyHandler in the last code block(for MyEvent) Answers will be very much appreciated.
Upvotes: 1
Views: 907
Reputation: 328598
Simply change the MyEvent
class declaration:
public static class MyEvent extends SomeEvent<MyHandler> { ... }
and it should be fine.
Upvotes: 0
Reputation: 78579
I think it should be
public class MyEvent<T extends MyHandler> extends SomeEvent<T> {
public void executeHandlers() {
for (T handler : handler_list) {
//Exception here!!
handler.startEventAction(lvc_count);
}
}
If you use MyEvent<MyHandler>
you're considering MyHandler
as a type parameter, not as a type argument. That's why I typically rather use letters as type paramers instead of entire words, this avoids the confusion between them and classes and interfaces names.
Upvotes: 2