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<T, This extends Addable<T, This>> {
public This add(T t);
}
Now declare a level of indirection - a "template" class
public interface ListTemplate<A, This extends ListTemplate<A, This>>
extends Addable<A, This>{
}
public interface List<A> extends ListTemplate<A, List<A>> {
}
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<A> implements List<A> {
public List<A> 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?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…