• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Return type of method in subclass differ from return type in parentclass

 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This code does not compile.



The whizlab answer states that the given code does not compile because the method in the subclass differ only in the return type; its not legal. If the argument had been different, it would have been a case of overloading.

In my opinion it does not compile because of the "int" of the print method is not a identical to Integer or one of (Integers) subclasses. Thats why you cannot compile this.

What do you say?

Thanks.
 
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So both your and whizlabs statements are correct.

To override a method you need to keep the exact same signature, except for covariant return types and exceptions that need to be the same, narrowed or not existent at all in the overriding class.
 
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think you've understood it right. If the return type of the overriding method was Integer (or a sub-class as per covariant return types, but Integer class is final so not applicable here) then the code would've compiled fine. The answer in whizlabs also says the same thing, but they also explain that if the print method in sub-class had different arguments, then there would've been overloading and thus the code would've compiled fine...
 
reply
    Bookmark Topic Watch Topic
  • New Topic