Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the Java compiler perform type erasure for lower bounded wildcards?

Tags:

java

oop

generics

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?

like image 394
Pawan Avatar asked Aug 25 '14 06:08

Pawan


People also ask

What is a lower bounded wildcard in JavaScript?

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>.

What is type erasure in Java with example?

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.

Is it possible to specify upper and lower bounds for wildcards?

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.

How does the Java compiler preserve polymorphism of generic types after erasure?

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.


1 Answers

For super type,it erases to Object type.<?super T> is only used for compile time verification

like image 149
Kumar Abhinav Avatar answered Oct 02 '22 07:10

Kumar Abhinav