While compiling source code with generic types, the Java compiler automatically performs type erasure, replacing the generic declarations with suitable raw types.
As per the Oracle docs, this erasure replaces the upper bonded wildcard <? extends T>
with T. This fits well with dynamic polymorphism.
But how is this erasure performed for lower bounded wildcard <? super T>
seeing that every class has a common super class (Object), using which will defeat the whole purpose?
In a similar way, a lower bounded wildcard restricts the unknown type to be a specific type or a super type of that type. A lower bounded wildcard is expressed using the wildcard character ('? '), following by the super keyword, followed by its lower bound: <? super A>.
Type Erasure in Java. Generics concept is introduced in Java language to provide tighter type checks at compile time and to support generic programming. The way to implement generics, the Java compiler applies type erasure to: Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded.
Note: You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both. Say you want to write a method that puts Integer objects into a list.
In our example above, the Java compiler preserves polymorphism of generic types after erasure by ensuring no method signature mismatch between IntegerStack ‘s push (Integer) method and Stack ‘s push (Object) method. Consequently, Stack class's push method after type erasure, delegates to the original push method of IntegerStack class.
For super type,it erases to Object type.<?super T>
is only used for compile time verification
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With