Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

inheritance

 
Sandra Dakurah
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic