The Artima Developer Community
Sponsored Link

Java Answers Forum
java.util.Collection type casting

1 reply on 1 page. Most recent reply: Aug 6, 2006 6:35 PM by Kishori Sharan

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Gerrit

Posts: 4
Nickname: sifman
Registered: Sep, 2005

java.util.Collection type casting Posted: Aug 6, 2006 1:07 PM
Reply to this message Reply
Advertisement
Hi,

I'm stumped:

This is legal (note that it is obviously only legal at compile time):
Collection collection = new ArrayList();
Room s = (Room) collection;

This is not legal at compile time:
ArrayList collection = new ArrayList();
Room s = (Room) collection;

My question is: Howcome it is (compile-time) possible to have java.util.Collection as a legal super of ANY type, even if it is not in the class hierarchy of these other types.

Thanks,
Gerrit


Kishori Sharan

Posts: 211
Nickname: kishori
Registered: Feb, 2002

Re: java.util.Collection type casting Posted: Aug 6, 2006 6:35 PM
Reply to this message Reply
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;

Flat View: This topic has 1 reply on 1 page
Topic: .class file attributes Previous Topic   Next Topic Topic: Need a generic algorithm

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use