Is there a way to say \"this method returns this
\" using Generics?
Of course, I want to override this method in subclasses, so the declaration should wo
You can do something very clever (and akin to what they have done in Scala with the 2.8 collection framework). Declare some interface method that should return "itself" (Note: This
is a type parameter, not a keyword!)
public interface Addable> {
public This add(T t);
}
Now declare a level of indirection - a "template" class
public interface ListTemplate>
extends Addable{
}
public interface List extends ListTemplate> {
}
Then an implementation of List
has to return a List
from the add
method (I'll let you fill in the impl details)
public class ListImpl implements List {
public List add(A a) {
return ...
}
}
Similarly you could have declard a SetTemplate
and a Set
to extend the Addable
interface - the add
method of which would have returned a Set
. Cool, huh?