CKTIS / Java
Recursive type bounds in Java
A bound such as `T extends Base<T>` lets base-class methods return a concrete subclass type without requiring every subclass to supply its own type.
Version: Java SE 21
Syntax
abstract class Base<T extends Base<T>> { /* ... */ }
final class Report extends Base<Report> { /* ... */ }In Base<T extends Base<T>>, the first T declares a type parameter, and extends sets its upper bound. The bound is recursive because Base<T> uses that same T as its type argument. For a concrete argument X, the compiler checks that X is a subtype of Base<X>. That is why Base<String> is a compile-time error.
In Report extends Base<Report>, extends names the direct superclass of Report. With T set to Report, the inherited withCopies method has return type Report at the call site, so you can call describe() next without a cast. Inside the base class, this has type Base<T>, not T. The base method therefore calls the abstract self() method, whose implementation in Report returns this.
This is a self-type pattern, not a guarantee that the type argument names the class of the current object. The declaration abstract class Other extends Base<Report> {} is legal: the bound checks Report, not Other. The standard library uses a similar bound in Enum<E extends Enum<E>>.
Examples
public class Main {
static abstract class Base<T extends Base<T>> {
private int copies = 1;
final T withCopies(int value) {
copies = value;
return self();
}
final int copies() {
return copies;
}
protected abstract T self();
}
static final class Report extends Base<Report> {
@Override
protected Report self() {
return this;
}
String describe() {
return "Report copies: " + copies();
}
}
public static void main(String[] args) {
System.out.println(new Report().withCopies(3).describe());
}
}Result
Report copies: 3
`withCopies(3)` sets the copy count and returns the same `Report` object through `self()`. The chain can then call `describe()`, and the program prints `Report copies: 3`.
Related lessons
- Java · Lesson 3 · Advanced · Version: 2