This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 1817

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:
subject: inheritance
Similar Threads
Class/Sub Class
Please explain(about accessing members)!
Super and sub class
Basic Java Question