Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dout about overloaded methods

 
jack borton
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone,

I was reading my book SCJP (authors: Kathy Sierra and Bert Bates) and when practicing about an exercise (page 112), there is something wrong.
I want to know if you can see if I missed something.


Second class.


Finally, the class that test the overloaded methods



The code printed is:
Generic animal eating ....
The horse is eating ....

They said that the overloaded method called is based on the reference type of the argument passed at compile time. So the answer must be twice the message "Generic animal eating .... ".
I missed something?

Thank you.
 
Matthew Brown
Bartender
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The overloaded method called depends on the reference type. But both doStuff methods do the same thing...they call the eat() method.

And the overridden method called depends on the actual type of the object, which is why you get the result you see.

If you put print statements in the two doStuff methods, you'd see that doStuff(Animal a) is being called twice.
 
jack borton
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Thank you. I forgot that I was mixing overloaded and overriding methods.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic