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

Overriding confusion - Please help!

 
Sharda Vajjhala
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider this:

Output is:
5
Me, I'm a Cyborg
If I am instantiating Cyborg, shouldn;t it print 10 instead of 5?
(edited by Cindy to format code)
[This message has been edited by Cindy Glass (edited November 13, 2001).]
 
Fei Ng
Ranch Hand
Posts: 1245
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instance Var dont get overriden.
so printout is int power = 5
But you can hide them in your subclass.
In your case you are using the
reference Robot so it will print out Robot's
int power.
But if you use the Cyborg's reference
Cyborg's int power will be printed.
And thats hiding Robot's int power in
Cyborg.


[This message has been edited by FEI NG (edited November 13, 2001).]
 
Marium Hasan
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hello,
The fact is that:
a) instance method is always called of which instance (i.e Cyborg )is created.
b) However, keep in mind that when an instance variable is used, it will always be of the type of class . here, in this case is Robot.
Since Robot rm = new Cyborg();
Hope it helps & check this for yourself by practising.
Regards,
Marium
 
Colin Kenworthy
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this,
In your Robot and Cyborg classes add this method...
public int getPower() {
return this.power;
}
...then in class TestCyborg instead of printing ry.power, print ry.getPower()
System.out.println(ry.getPower())
I too expected to see 10, so thanks everyone for the explanations. You learn something new everyday. :-)
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
svajjh02,
Please change your name to be compliant with JavaRanch's naming policy.
Your ID should be 2 separate names with more than 1 letter each and not obviously fictional. We would prefer that you use your REAL name.
Thanks,
Cindy
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic