I'd like to know what the effect is when you have two fields of the same name in a superclass and subclass. Something along the lines of:
int x = 0;
class Derived extends Base
int x = 1;
If I store a reference to a Derived object in a Base reference variable called base and I do base.x I get 0.
If I store the reference in a Derived reference variable called der and I do der.x I get 1.
Are there actually two fields with name x in instances of Derived?
Edited by: 953012 on Mar 24, 2013 4:32 PM
Edited by: 953012 on Mar 24, 2013 4:33 PM
And once again you need to review The Java Language Spec. It answers questions like yours and has examples. See the examples.
Example 126.96.36.199-3. Hiding of Instance Variables
. . .
because the declaration of x in class Test hides the definition of x in class Point, so class Test does not inherit the field x from its superclass Point. It must be noted, however, that while the field x of class Point is not inherited by class Test, it is nevertheless implemented by instances of class Test. In other words, every instance of class Test contains two fields, one of type int and one of type double. Both fields bear the name x, but within the declaration of class Test, the simple name x always refers to the field declared within class Test. Code in instance methods of class Test may refer to the instance variable x of class Point as super.x.
Code that uses a field access expression to access field x will access the field named x in the class indicated by the type of reference expression. Thus, the expression sample.x accesses a double value, the instance variable declared in class Test, because the type of the variable sample is Test, but the expression ((Point)sample).x accesses an int value, the instance variable declared in class Point, because of the cast to type Point.
Did you see this part? 'every instance of class Test contains two fields, one of type int and one of type double'