This discussion is archived
2 Replies Latest reply: Mar 24, 2013 5:45 PM by rp0428 RSS

Same field name in superclass and subclass

956015 Newbie
Currently Being Moderated
Hi,

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:
class Base
{
   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?

Thank you.

Edited by: 953012 on Mar 24, 2013 4:32 PM

Edited by: 953012 on Mar 24, 2013 4:33 PM
  • 1. Re: Same field name in superclass and subclass
    rp0428 Guru
    Currently Being Moderated
    And once again you need to review The Java Language Spec. It answers questions like yours and has examples. See the examples.
    http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#d5e10238
    >
    Example 8.3.1.1-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'
  • 2. Re: Same field name in superclass and subclass
    956015 Newbie
    Currently Being Moderated
    Hi,

    Thank you for the link, it answered my questions.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points