Java覆盖抽象泛型方法

时间:2011-07-05 16:46:12

标签: java generics abstract-class custom-attributes

我有以下代码

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
}

但我不知道该怎么做,因为我不能用特定的东西覆盖doEventStuff

有谁知道怎么做?

3 个答案:

答案 0 :(得分:17)

你要做的事情并不是很清楚,但也许你只需要Event本身是通用的:

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

答案 1 :(得分:7)

您使用的是泛型,但您没有提供绑定。

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

或仅使用一个通用绑定更简单...

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

答案 2 :(得分:0)

这仍然对我不起作用。我有以下代码:

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

既然 MyConcreteContainer 是泛型 Container 的实现,为什么我的编译器不能识别我已经正确地重写了 doStuff 方法?