|
|
Re: java.util.Collection type casting
|
Posted: Aug 6, 2006 6:35 PM
|
|
Please read the first rule at the link: http://java.sun.com/docs/books/jls/second_edition/html/conversions.doc.html#175725
In case of an interface being cast to a class, Java doesn't check the class hierarchy. So, the following compiles. Collection collection = new ArrayList(); Room s = (Room) collection;
For example, above code may be fine at runtime if Room class implements Collection interface as: Collection collection = new Room(); Room s = (Room) collection;
In fact, Java compiler is least worried about the first statement: Collection collection = new ArrayList();
in which you have assigned an ArrayList object to Collection variable type. It only considers, Room s = (Room) collection; and sees that "collection" is an interface and lets it pass the test.
However, in case of a class being cast to another class, both of them must be related by inheritance. Otherwise, it is a compile time error as in case below.
ArrayList collection = new ArrayList(); Room s = (Room) collection;
|
|