aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics and Overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics and Overriding" Watch "Generics and Overriding" New topic
Author

Generics and Overriding

Anup Om
Ranch Hand

Joined: Dec 30, 2009
Posts: 62
Code Sample # 1

Code Sample # 2



Why is code sample#1 a valid override where as code sample#2 is not a valid override?

Thanks for your help.


SCJP6
Kamil Wojcik
Ranch Hand

Joined: May 19, 2008
Posts: 78

This is because Java Generics are implemented with Type Erasure: HERE


SCJP 6.0 Passed | SCWCD Passed | PSM in progress...
Anup Om
Ranch Hand

Joined: Dec 30, 2009
Posts: 62
Kamil Wojcik wrote:This is because Java Generics are implemented with Type Erasure: HERE


Even then, why is code sample#1 valid? What am I missing?

Thanks
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18997
    
  40

Anu Kota wrote:
Even then, why is code sample#1 valid? What am I missing?


Basically, when a subclass overrides a method, with generics involved, the subclass has to be able to handle all the cases of the super class -- after all, the subclass IS-A super class, and if the subclass can't deal with the super class parameters, it isn't overriding.

In example #2, the subclass can only take a List<Integer>, which means it can't handle a List<String>... hence, it isn't overriding, it's overloading. But with type erasure, it can't be overloading, hence, compile error.

In example #1, the subclass takes a List (without generics), which means it can handle any list, including the List<String> of the superclass. Hence, it is overriding.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Anup Om
Ranch Hand

Joined: Dec 30, 2009
Posts: 62


Why wouldn't this compile? List<?> can handle any list including List<Integer>. I surely missed something from your explanation above.

EDIT: I think I understand this. Methods 'say' will be considered as overloads and not overrides. But, due to type erasure, they are not valid overrides. Same as Code sample#2 in first post. Am I right?

Thanks,
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Generics and Overriding