Course contentsShow
← Java
Lesson 894 of 2,87021. Generics FundamentalsFree lesson

Bounded Type Parameters Become Their Bound

Understanding that <T extends Number> erases to Number, not Object, in the compiled bytecode.

Bounded Type Parameters Become Their Bound

You'll learn how bounded type parameters are erased to their specific bound type, not to Object.

The Core Idea

In the previous lesson, you learned that generic type parameters are erased to Object during compilation. However, when you use bounded type parameters (like <T extends Number>), the erasure works differently: the type parameter is erased to its bound instead of Object.

This means <T extends Number> becomes Number in the bytecode, <T extends Comparable> becomes Comparable, and so on.

Why This Matters

The compiler needs to know what methods are safe to call on T. If you write <T extends Number>, the compiler ensures you can call any Number method on instances of T. After erasure, those calls must still work—so T becomes Number in the compiled code, preserving access to Number's methods like doubleValue() or intValue().

The Difference

// Unbounded: T erases to Object
public class Box<T> {
    private T value;
    // After erasure: private Object value;
}

// Bounded: T erases to Number
public class NumberBox<T extends Number> {
    private T value;
    // After erasure: private Number value;
}

In NumberBox, any operations you perform on value that use Number methods will compile correctly because the bytecode guarantees value is a Number, not just any Object.

Multiple Bounds

When you have multiple bounds like <T extends Number & Comparable>, the type erases to the first bound (Number in this case), with additional interface casts inserted where needed.

Key Takeaway:
Bounded type parameters erase to their bound type (e.g., <T extends Number> → Number), allowing safe method calls on the bound class while maintaining backward compatibility.