jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Overriding confusion - Please help! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Overriding confusion - Please help!" Watch "Overriding confusion - Please help!" New topic

Overriding confusion - Please help!

Sharda Vajjhala

Joined: Nov 12, 2001
Posts: 2
Consider this:

Output is:
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

Joined: Aug 26, 2000
Posts: 1242
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

[This message has been edited by FEI NG (edited November 13, 2001).]
Marium Hasan

Joined: Oct 03, 2001
Posts: 12

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.
Colin Kenworthy
Ranch Hand

Joined: Aug 06, 2001
Posts: 88
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()
I too expected to see 10, so thanks everyone for the explanations. You learn something new everyday. :-)
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
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.

"JavaRanch, where the deer and the Certified play" - David O'Meara
I agree. Here's the link: http://aspose.com/file-tools
subject: Overriding confusion - Please help!
It's not a secret anymore!