• 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

Problem with return type in an overriden method

 
Greenhorn
Posts: 6
Netbeans IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Given this code:


if i run this code i get

Why I need to cast (String)a.voice() if the method called is a Dog Class member and has a String return type?
if i put the cast, y get

bark

 
Sheriff
Posts: 3837
66
Netbeans IDE Oracle Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You've declared the variable as Animal, and Animal.voice() returns Object. Although you know that the variable a contains an instance of Dog, the compiler does not "know" it and therefore expects that a.voice() returns Object.

This behavior of the compiler is not an error, it was designed this way. This is a trivial case. However, there might be cases in which such conclusions about actual type of a variable (if at all possible) might require extensive analysis. Therefore, the compiler follows a simple rule: a type of the variable is always determined by its declared type, regardless of its actual contents.
 
Martin Vashko
Sheriff
Posts: 3837
66
Netbeans IDE Oracle Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
... and welcome to the Ranch!
 
Xavier Figueroa
Greenhorn
Posts: 6
Netbeans IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you so much for your answer, I really needed this clarification and thanks for your Welcome
 
So there I was, trapped in the jungle. And at the last minute, I was saved by this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic