使用Java中的泛型参数(必须扩展泛型类)扩展抽象方法

时间:2015-07-12 02:25:21

标签: java generics abstract-class

假设我有一个通用的构建器类型:

public abstract class Builder<T> {

  public abstract T build();
}

然后是Foo类和它的构建器,它扩展了Builder:

public class Foo {
  // stuff
}

public class FooBuilder extends Builder<Foo> {

  public Foo build() {
    return new Foo();
  }
}

我还有一个抽象的通用处理程序类型:

public abstract class Handler<T> {

  public abstract <U extends Builder<T>> void handle(U builder);
}

最后是FooHandler:

public class FooHandler extends Handler<Foo> {

  @Override
  public void handle(FooBuilder builder) {
    // do something
  }
}

问题是FooHandler的handle()无法识别为覆盖Handler的句柄():Method does not override method from its superclass。有可能这样做吗?

1 个答案:

答案 0 :(得分:2)

将type参数移动到类级别

abstract class Handler<T, U extends Builder<T>> {
    public abstract void handle(U builder);
}

class FooHandler extends Handler<Foo, FooBuilder> {
    @Override
    public void handle(FooBuilder builder) {
        // do something
    }
}