Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 601
iuiz Avatar asked Jul 05 '11 16:07

iuiz


People also ask

Can you override an abstract method in Java?

A subclass must override all abstract methods of an abstract class. However, if the subclass is declared abstract, it's not mandatory to override abstract methods.

Can we override non-abstract method of abstract class in Java?

"Is it a good practice in Java to override a non-abstract method?" Yes.

Can methods in abstract class be overridden?

An abstract method is a method that is declared, but contains no implementation. you can override both abstract and normal methods inside an abstract class. only methods declared as final cannot be overridden.

How can we override abstract method in non-abstract class?

A non-abstract child class of an abstract parent class must override each of the abstract methods of its parent. A non-abstract child must override each abstract method inherited from its parent by defining a method with the same signature and same return type. Objects of the child class will include this method.


1 Answers

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)
    {
        ...
    }
}
like image 59
Jon Skeet Avatar answered Sep 21 '22 14:09

Jon Skeet