Java Generics – No Cast

Java Generics - No Cast

This topic is about Java Generics – No Cast.

Casting to a parameterized type is not allowed unless it is parameterized by unbounded wildcards.

Box<Integer> integerBox = new Box<Integer>();
Box<Number> numberBox = new Box<Number>();
//Compiler Error: Cannot cast from Box<Number> to Box<Integer>
integerBox = (Box<Integer>)numberBox;

To achive the same, unbounded wildcards can be used.

private static void add(Box<?> box) {
   Box<Integer> integerBox = (Box<Integer>)box;
}

In this topic we learned about Java Generics – No Cast. To know more, Click Here.

Leave a Reply