Bridge Methods for Type Safety
What you'll learn: How the Java compiler secretly inserts synthetic "bridge" methods to keep polymorphism working correctly after generics are erased at runtime.
The Problem After Erasure
You've learned that type erasure replaces type parameters with Object (or their bound). This creates a hidden problem: when you override a generic method in a subclass, the erased signatures might not match, breaking polymorphism.
Imagine this scenario:
class Node<T> {
private T data;
public void setData(T data) {
this.data = data;
}
}
class IntegerNode extends Node<Integer> {
@Override
public void setData(Integer data) {
// Custom implementation
}
}
After erasure, Node has setData(Object), but IntegerNode has setData(Integer). These are different signatures—one doesn't actually override the other! Polymorphism would fail.
The Compiler's Solution: Bridge Methods
To fix this, the compiler automatically generates a synthetic bridge method in IntegerNode:
// Generated by compiler (not visible in source)
public void setData(Object data) {
setData((Integer) data); // Delegates to the real method
}
This bridge method matches the erased signature from the parent class, preserves the override relationship, and delegates to your setData(Integer) implementation. The cast is safe because generic type checking already happened at compile time.
Why It Matters
Bridge methods are invisible to you but essential—they ensure that generic code behaves polymorphically even after erasure strips away type information. Without them, calling setData through a Node reference would invoke the wrong method.
Key Takeaway:
The compiler generates synthetic bridge methods to maintain correct method overriding and polymorphism after type erasure converts generic signatures to their raw forms.