This is possible with generics using the following construction:
public class ParentType<T extends ParentType<T>> { public T withId(String someId) { return (T) this; } } public class BranchType<T extends BranchType<T>> extends ParentType<T> {} public final class LeafTypeA extends BranchType<LeafTypeA> {} public final class LeafTypeB extends ParentType<LeafTypeB> {}
Where BranchType is a class with subclasses, and LeafTypeA, LeafTypeB are classes without subclasses.
This is a slight improvement over the other generic solution, as it prevents:
public class LeafTypeA extends BranchType<LeafTypeB> {}
Since this does not satisfy the restrictions of the type parameter.
Cyberian tiger
source share