简体   繁体   中英

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?

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)
    {
        ...
    }
}

You're 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 simpler with only one generic 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) {
  }
}

This is still not working for me. I have the following code:

public interface Container<T extends MyEntity> {
...
}


public class MyConcreteContainer implements Container<MyContreteEntity> {
   ...
}

public abstract class MyAbstractClass<T extends MyEntity> {

  public abstract String doStuff(Container<T> container);
}

public class MyConcreteEntity implements MyEntity {
   ...
}

public class MyConcreteImplementedClass extends MyAbstractClass<MyContreteEntity> {
  
  @Override
  public String doStuff(MyConcreteContainer container) {
    ...
  }
}

Since MyConcreteContainer IS AN implementation of the generic Container , why is my comppiler not recognising that I have Overridden the doStuff method correctly?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM