Hide Java fields

In the following scenario:

class Person{
    public int ID;  
}

class Student extends Person{
    public int ID;
}

Student "hides a person’s identifier field.

if we want to remember the following:

Student john = new Student();

will the john object have two SEPARATE memory locations for the Person.ID file to store and its own?

+3
source share
3 answers

Correctly. Each class in your example has its own id field int ID.

You can read or assign values ​​this way from subclasses:

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 publicly available):

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

Yes, as you can check:

class Student extends Person{
    public int ID;

    void foo() {
        super.ID = 1;
        ID = 2;
        System.out.println(super.ID);
        System.out.println(ID);
    }
}
+5
source

, . ints.

Person int Student :

super.ID;

Be careful, dynamic dispatch is not performed for member fields. If you define a method for Person that uses a field ID, it will refer to the field Person, not Studentone, even if called in the object Student.

public class A
{
    public int ID = 42;

    public void inheritedMethod()
    {
        System.out.println(ID);
    }
}

public class B extends A
{
    public int ID;

    public static void main(String[] args)
    {
        B b = new B();
        b.ID = 1;
        b.inheritedMethod();
    }
}

The above will print 42, not 1.

+1
source

All Articles