wood burning stoves 2.0
The moose likes Beginning Java and the fly likes inheritance Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "inheritance" Watch "inheritance" New topic


Sandra Dakurah

Joined: Dec 01, 2004
Posts: 2
To my suprprise the code below gives as a result
5, sub.
Does anybody know he rule behind this?

[JAM -- Edited to include [CODE] and [/CODE] tags]
[ December 10, 2004: Message edited by: Joel McNary ]
Joel McNary

Joined: Aug 20, 2001
Posts: 1824

The reason for this is that some decisions are made at compile-time and others at run-time. The decisions that are made at run-time are those that implement polymorphism -- the ability to override methods in super classes to acheive different effects.

You have member variables with the same name in a super- and a sub-class (as your index variable is). Only method calls participate in polymorphism -- that is, it will determine which method to call at runtime. (Caveat: Which version of an overloaded method to use is determined at compile-time. Of course, which class's version of the selected method is a run-time decision).

Thus, the compiler has to determine which version of index to use. Since the reference type is of type Super, it uses's Super's index. (The compiler cannot know the actual class type, since it's not run-time. It can only know the reference type -- what type did you call your variable.)

Compare the result with the result of changing Sub to look like the following:

[ December 10, 2004: Message edited by: Joel McNary ]

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
I agree. Here's the link: http://aspose.com/file-tools
subject: inheritance
It's not a secret anymore!