Saturday, September 11, 2010

Java Generics - Part 3

List<Student> is NOT a List<Person>.

Isa relationships do not apply for generics. Why? Check the following listing:


 

1        List<String> nameList = new ArrayList<String>();

2        List<Object> objectList = nameList; // Now objectList is an alias for nameList

3     obecjtList.add( new Student() ); // a Student would have been added to a List<String>


 

Assuming the above code snippet would compile (it will not), it has introduced a Student object into a List of Strings. This violates one of the very basic reasons for having generics (type checking).  So Isa relationships do not work with generics.

BTB, the above code will fail compilation with the following compiler error:


 

NoIsaInGenerics.java:8: incompatible types

found   : java.util.List<java.lang.String>

required: java.util.List<java.lang.Object>

               List<Object> objectList = nameList; // Now objectList is an alias for nameList

                                         ^

NoIsaInGenerics.java:9: cannot find symbol

symbol  : variable obecjtList

location: class NoIsaInGenerics

               obecjtList.add( new Student() ); // a Student would have been added to a List<String>

               ^

2 errors


 

No comments: