{"id":"019cd7da-dc57-71b2-a247-27b894060e28","title":"F-Bounded Polymorphism: Type-Safe Builders in Java","slug":"2026/03/f-bounded-polymorphism-type-safe-builders-in-java-2","renderedHtml":"<p>In &quot;<a href=\"https://www.fbounded.com/blog/f-bounded-polymorphism\">F-Bounded Polymorphism: Type-Safe Builders in Java</a>&quot;,  author &quot;fbounded&quot; addresses what he calls a fundamental inheritance problem in Java's fluent builder pattern.</p>\n<p>When a base builder class returns <code>this</code>, subclass methods lose type information - calling a parent method on <code>CarBuilder</code> returns <code>VehicleBuilder</code>, breaking the method chain, because <code>this</code> loses the <em>reference type</em> of being a <code>CarBuilder</code>, being a <code>VehicleBuilder</code> instead.</p>\n<p>The fix uses a self-referential type bound: <code>VehicleBuilder&lt;B extends VehicleBuilder&lt;B&gt;&gt;</code> declares that <code>B</code> must be a subtype of <code>VehicleBuilder</code> parameterized by itself. Concrete builders then extend <code>VehicleBuilder&lt;CarBuilder&gt;</code>, allowing base class methods to return the actual subclass type without casts.</p>\n<p>This pattern appears throughout the Java standard library. <code>Enum&lt;E extends Enum&lt;E&gt;&gt;</code> uses the same technique to ensure <code>Planet.compareTo()</code> only accepts another <code>Planet</code>, not any <code>Enum</code>, turning potential runtime errors into compile-time guarantees. The <code>Comparable</code> interface follows similar logic.</p>\n<p>The approach scales cleanly to multiple subclasses - each declares itself as its own type parameter - but struggles with deeper inheritance hierarchies where a subclass of <code>CarBuilder</code> cannot re-specialize the already-bound <code>B</code> parameter.</p>\n<p>In practice, one level of builder inheritance handles most real-world cases, making F-bounds a practical solution rather than theoretical curiosity. The unchecked cast to <code>B</code> remains necessary in the base class implementation but is hidden from client code, preserving type safety at call sites.</p>\n<p>Interesting article.</p>","excerpt":"In F-Bounded Polymorphism: Type-Safe Builders in Java , author fbounded addresses what he calls a fundamental inheritance problem in Java's fluent builder pattern. When a base builder class returns...","authorId":"019c5c8a-609d-7cd4-975b-50bbcc412a33","authorDisplayName":"dreamreal","status":"APPROVED","publishedAt":"2026-03-10T13:11:33.435Z","sortOrder":0,"createdAt":"2026-03-10T13:06:10.645112Z","updatedAt":"2026-03-10T13:11:33.562481Z","commentCount":0,"tags":["builders","design patterns","generics","java","type systems"],"categories":[],"markdownSource":null}