• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Rob Spoor
  • Devaka Cooray
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Jj Roberts
  • Al Hobbs
  • Piet Souris

inheritance

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Bartender
Posts: 1843
Eclipse IDE Ruby Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic