posted 16 years ago
Hi,
When you have a declaration for an instance method in a subclass that has the same name and argument list as an instance method in a superclass, you are attempting (you also must abide by the rules for proper overriding in order for this to be a successful override) to override the method.
However, when you have a declaration for a variable in a subclass that has the same name as a variable in the superclass, you are not overriding it (same goes for static methods.) In that case, you just define an additional variable (or static method) that will shadow the superclass' namesake.
The only factor that comes into play when you want to figure out what variable you are retrieving is the type of the reference you are retrieving it through (because the overriding mechanism is not active for variables or static methods.) So, above, f is of type Foo, and therefore f.a will retrieve the variable a defined in Foo. If you do ((Bar)f).a, then you will pick up the variable a defined in Bar.
(To clarify: If a weren't declared in Bar, ((Bar)f).a would still retrieve the a defined (defined as in visible) in Bar. It's just that, in that case, Bar would inherit the a from Foo, without declaring a new variable a, and shadowing the one declared in Foo.)
The main thing to remember is that for variable and static method references you are just retrieving them from a declaration scope (the type of the reference) at compile time, whereas for instance methods, you use the overriding mechanism to decide at run time, based on the type of the actual object the reference variable is bound to, which version of the overriding method set to invoke.
I hope that clarifies things a little.
[ January 02, 2009: Message edited by: Ruben Soto ]
All code in my posts, unless a source is explicitly mentioned, is my own.