File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Overriding confusion - Please help!" Watch "Overriding confusion - Please help!" New topic
Author

Overriding confusion - Please help!

Sharda Vajjhala
Greenhorn

Joined: Nov 12, 2001
Posts: 2
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

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
Cyborg.


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

Joined: Oct 03, 2001
Posts: 12

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

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()
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

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

"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!