library
advancedCovariant Return Types & Bridge Methods
Understand method overriding with narrower return types and the invisible bridge methods the compiler generates.
Covariant return types (Java 5) allow an overriding method to return a more specific type than the parent method.
Covariant return = a factory that advertises 'produces vehicles' (parent) but a subsidiary actually produces 'sports cars' (child). The subsidiary's product IS a vehicle (still compatible), just more specific. Bridge method = a redirect sign at the factory entrance that sends visitors to the sports car line.
Key Concepts
1
class Animal {
Animal create() { return new Animal(); }
}
class Dog extends Animal {
@Override
Dog create() { return new Dog(); } // narrower return type — legal!
}
2
Without covariant returns, Dog.create() would have to return Animal, requiring callers to cast.
3
Bridge methods: the compiler generates synthetic bridge methods to maintain binary compatibility with pre-generics code. A bridge method has the erased signature (returns Object) and delegates to the actual method (returns Dog).
4
Generic bridge methods:
interface Comparable<T> { int compareTo(T o); }
class MyClass implements Comparable<MyClass> {
int compareTo(MyClass o) { ... } // actual method
// Compiler generates bridge:
// int compareTo(Object o) { return compareTo((MyClass)o); }
}
5
Bridge methods are marked with ACC_BRIDGE in the bytecode. You can see them with javap -v. Reflection: Method.isBridge() returns true for bridge methods.
6
You rarely need to think about bridge methods — they're an implementation detail. But they explain why you sometimes see unexpected methods in reflection or debugger output.