Skip to content
Advertisement

Java override 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 don’t know how to do this, as I cannot override doEventStuff with something specific.

Does anyone know how to do this?

Advertisement

Answer

It’s not really clear what you’re 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)
    {
        ...
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement