Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Java in General and the fly likes Why isn't this generics based instantiation working? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why isn Watch "Why isn New topic
Author

Why isn't this generics based instantiation working?

Yuriy Zilbergleyt
Ranch Hand

Joined: Dec 13, 2004
Posts: 429
The first statement works, but the second one does not compile.



Why did they design generics in a way to disallow something that seems (to me at least) to be a clear cut case of polymorphism?

Thanks,
Yuriy
Marco Ehrentreich
best scout
Bartender

Joined: Mar 07, 2007
Posts: 1278

Hi Yuriy,

consider the following small example. It shows what could happen if it would be allowed what you think.

I hope this gives some explanation why this would be bad and usually not what you want.

Marco
amitabh mehra
Ranch Hand

Joined: Dec 05, 2006
Posts: 98
Here, polymorphism applies to the "base" i.e. the collection class and not to the generic.
If we compare this with polymorphism with arrays, then at runtime, JVM knows the type of arrays but in case of collection this information is not available because of type erasure. All the generic type info is removed during compilation.

Also, for arrays there is runtime exception - java.lang.ArraySortException available. Nothing of this sort in collections. So all checks are done at compile time.

Hence, at base type there can be polymorphism but not for generic type.

Hope this answers your question.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36508
    
  16
More about this in the Java Tutorials. Look up bounded types and subtyping.
Yuriy Zilbergleyt
Ranch Hand

Joined: Dec 13, 2004
Posts: 429
Heh Marco, I didn't think of that.
Nitesh Kant
Bartender

Joined: Feb 25, 2007
Posts: 1638

amitabh:- java.lang.ArraySortException available.

I think you meant ArrayStoreException.


apigee, a better way to API!
amitabh mehra
Ranch Hand

Joined: Dec 05, 2006
Posts: 98
Originally posted by Nitesh Kant:

I think you meant ArrayStoreException.


ya .... sorry for the typo.. my bad
arulk pillai
Author
Ranch Hand

Joined: May 31, 2007
Posts: 3216


Java Interview Questions and Answers Blog | Amazon.com profile | Java Interview Books
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why isn't this generics based instantiation working?
 
Similar Threads
Generics
Generics
Generics Generics Generics !!!
generics
Generics