Returning an objects subclass with generics

Sarabjot picture Sarabjot · Jul 19, 2010 · Viewed 20.4k times · Source

With an abstract class I want to define a method that returns "this" for the subclasses:

public abstract class Foo {
    ...
    public <T extends Foo> T eat(String eatCake) {
        ...
        return this;
    }
}  

public class CakeEater extends Foo {}

I want to be able to do things like:

CakeEater phil = new CakeEater();
phil.eat("wacky cake").eat("chocolate cake").eat("banana bread");

Arguably banana bread would throw an IllegalArgumentException with the message "Not a cake!"

Answer

irreputable picture irreputable · Jul 19, 2010
public abstract class Foo<T extends Foo<T>>  // see ColinD's comment
{
    public T eat(String eatCake) 
    {
        return (T)this;
    }
}

public class CakeEater extends Foo<CakeEater> 
{
    public void f(){}
}

Edit

There is no problem to require subclass behave in a certain way that's beyond what static typing can check. We do that all the time - pages and pages of plain english to specify how you write a subclass.

The other proposed solution, with covariant return type, must do the same - asking subclass implementers, in plain english, to return the type of this. That requirement cannot be specified by static typing.