Icon

Software Engineering, Architecture, Web Development and beyond…

Java Generics in Action: Inheritance between generic types

One of the most common asked question about generics is why Java doesn’t support assignment of inherited parameterized types.

The Situation:

class Sub extends Base {...}
 
List<Base> list = new ArrayList<Sub>(); // won't be compiled.

The Code above won’t be compiled! Even, this problem will be caught by your clever IDE (Eclipse,NetBeans etc.), before you hit compilation button. But what is wrong with it ?

Note that: The parameterized types will be checked by compiler in “compile-time”, not in run-time. After the compiler validated your generic types, they are no more needed in byte code.

Assume that we could make such an assignment. Now let us consider the following:

LinkedList<Integer> intList = new LinkedList<Integer>();
// assume that it is valid
LinkedList<Number> numList = intList; 
//  we try to put some double objects into the Integer list.
numList.add(new Double(3.14));

Assume that we had a method which took a parameter of List<Number>

public void makeSomethingWithList(List<Integer> list) { 
    // we trusted on our list which must give us back Integer objects!
    // but not. We get an unexpected Double object.
     Integer i = list.get(0); 
}

Surprisingly the method, which expects to get Integer objects from the list, gets a Double object instead an Integer one. To prevent this, java has an another issue, is called wildcards in generics.

Category: Java Programming

Tagged: , , , , , ,

Comments are closed.