Search code examples
javafieldmember-hiding

Java field hiding


In the following scenario:

class Person{
    public int ID;  
}

class Student extends Person{
    public int ID;
}

Student "hides ID field of person.

if we wanted to represent the following in the memory:

Student john = new Student();

would john object have two SEPARATE memory locations for storint Person.ID and its own?


Solution

  • Correct. Every class in your example has its own int ID id field.

    You can read or assign values in this way from the sub classes:

    super.ID = ... ; // when it is the direct sub class
    ((Person) this).ID = ... ; // when the class hierarchy is not one level only
    

    Or externally (when they are public):

    Student s = new Student();
    s.ID = ... ; // to access the ID of Student
    ((Person) s).ID = ... ; to access the ID of Person