aspose file tools
The moose likes Java in General and the fly likes Problem with return type in an overriden method Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Problem with return type in an overriden method" Watch "Problem with return type in an overriden method" New topic
Author

Problem with return type in an overriden method

Xavier Figueroa
Greenhorn

Joined: Apr 13, 2012
Posts: 6

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
Martin Vajsar
Bartender

Joined: Aug 22, 2010
Posts: 2331
    
    2

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 Vajsar
Bartender

Joined: Aug 22, 2010
Posts: 2331
    
    2

... and welcome to the Ranch!
Xavier Figueroa
Greenhorn

Joined: Apr 13, 2012
Posts: 6

Thank you so much for your answer, I really needed this clarification and thanks for your Welcome
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Problem with return type in an overriden method
 
Similar Threads
super generic and for loop
Reference Variable Casting?
Creating Objects
Doubt Example
About casting