Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics and Overriding

 
Anup Om
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Kamil Wojcik
Ranch Hand
Posts: 78
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is because Java Generics are implemented with Type Erasure: HERE
 
Anup Om
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21506
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
Anup Om
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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,
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic