Course contentsShow
← Java
Lesson 918 of 2,87022. Generics: Bounds and WildcardsFree lesson

Type Erasure and Bounded Type Parameters

How the compiler replaces bounded type parameters with their upper bound during type erasure.

Type Erasure and Bounded Type Parameters

What you'll learn: How the Java compiler replaces bounded type parameters with their upper bound during type erasure, rather than with Object.

The Core Idea

You've learned that type erasure removes generic type information at runtime, and that unbounded type parameters (like <T>) become Object. But what happens when you use bounded type parameters like <T extends Number>?

The compiler is smarter here: it replaces the type parameter with its upper bound instead of Object. So <T extends Number> becomes Number, <T extends Comparable<T>> becomes Comparable, and so on.

Why This Matters

This allows the compiler to preserve access to methods defined in the bound. When you write code that calls methods on T, the compiler ensures those methods exist in the bound type, then replaces T with that bound during erasure.

public class NumberBox<T extends Number> {
    private T value;
    
    public void printDouble() {
        // At compile time: T.doubleValue() is valid because Number has it
        // After erasure: becomes Number.doubleValue()
        System.out.println(value.doubleValue());
    }
}

After type erasure, the compiler has effectively rewritten this as if you'd declared private Number value; — not private Object value;.

The Benefit

This is why bounded type parameters give you compile-time safety and runtime method access. The bound ensures that after erasure, all the methods you called on T still exist on the replacement type.

Key Takeaway: During type erasure, bounded type parameters are replaced with their upper bound (the type after extends), not with Object, preserving access to the bound's methods at runtime.