Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 688
Bober02 Avatar asked May 30 '26 10:05

Bober02


2 Answers

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
like image 162
dash1e Avatar answered Jun 02 '26 01:06

dash1e


Yes, as you can verify with:

class Student extends Person{
    public int ID;

    void foo() {
        super.ID = 1;
        ID = 2;
        System.out.println(super.ID);
        System.out.println(ID);
    }
}
like image 28
meriton Avatar answered Jun 01 '26 23:06

meriton