dysfunction
dysfunction

Reputation: 159

Extending abstract method with generic parameter (that must extend generic class) in Java

Let's say I have a generic builder type:

public abstract class Builder<T> {

  public abstract T build();
}

Then a Foo class and a builder for it, which extends Builder:

public class Foo {
  // stuff
}

public class FooBuilder extends Builder<Foo> {

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

I also have an abstract, generic Handler type:

public abstract class Handler<T> {

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

and finally a FooHandler:

public class FooHandler extends Handler<Foo> {

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

The issue is that FooHandler's handle() is not recognized as overriding Handler's handle(): Method does not override method from its superclass. Is it possible to do this?

Upvotes: 3

Views: 1281

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279880

Move the type parameter to the class level

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

Upvotes: 3

Related Questions