Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

help on HFJ exercise

 
vidu sri
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


if object is created for both the classes and method is called,why the output is arrrgh arrrgh instead of
arrrgh and a bite?.

i could understand that the arguement differs and byte could not hold int,but still could not guess why the input is as like stated above.


 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because vampire's frighten method is overloaded, not overridden. The monster class doesn't know anything about that method.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34084
337
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vidu,
Let's walk through what the JVM "thinks" starting with the loop.
1) First iteration. I see you have this monster object and want to call frighten() on it with an int.
2) I see that method - I'll call it and print out "arrrgh".
3) Second iteration. I see you have this vampire object and want to call frighten() on it with an int.
4) I'll start by looking for matches in the subclass. Vampire has a frighten() method. I can't use it though since I have an int to pass and vampire only takes in a byte.
5) Moving on to the superclass - monster. Now I have a match.
 
Bhagat Singh Rawat
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

if object is created for both the classes and method is called,why the output is arrrgh arrrgh instead of
arrrgh and a bite?.

i could understand that the arguement differs and byte could not hold int,but still could not guess why the input is as like stated above.



See in 1st case you are creating an instance of monster and in 2nd case you creating instance of child class and assigning to parent class which is known as Polymorphism, therefore you are getting the same result in both cases. It means in the both cases the frighten method of monster class get called.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic