Java overrides abstract generic method

I have the following code

public abstract class Event { public void fire(Object... args) { // tell the event handler that if there are free resources it should call // doEventStuff(args) } // this is not correct, but I basically want to be able to define a generic // return type and be able to pass generic arguments. (T... args) would also // be ok public abstract <T, V> V doEventStuff(T args); } public class A extends Event { // This is what I want to do @Overide public String doEventStuff(String str) { if(str == "foo") { return "bar"; } else { return "fail"; } } } somewhere() { EventHandler eh = new EventHandler(); Event a = new A(); eh.add(a); System.out.println(a.fire("foo")); //output is bar } 

However, I do not know how to do this, since I cannot override doEventStuff with anything specific.

Does anyone know how to do this?

+7
source share
2 answers

It’s not entirely clear what you are trying to do, but perhaps you just need to make Event itself generic:

 public abstract class Event<T, V> { public abstract V doEventStuff(T args); } public class A extends Event<String, String> { @Override public String doEventStuff(String str) { ... } } 
+16
source

You are using generics, but you are not providing a binding.

 public abstract class Event<I, O> { // <-- I is input O is Output public abstract O doEventStuff(I args); } public class A extends Event<String, String> { // <-- binding in the impl. @Override public String doEventStuff(String str) { } } 

Or easier with one common binding ...

 public abstract class Event<T> { // <-- only one provided public abstract T doEventStuff(T args); } public class A extends Event<String> { // <-- binding the impl. @Override public String doEventStuff(String str) { } } 
+7
source

All Articles