Java字段隐藏

Bob*_*r02 3 java field member-hiding

在以下场景中:

class Person{
    public int ID;  
}

class Student extends Person{
    public int ID;
}
Run Code Online (Sandbox Code Playgroud)

学生"隐藏了人的身份证.

如果我们想在内存中表示以下内容:

Student john = new Student();
Run Code Online (Sandbox Code Playgroud)

john对象有storint Person.ID和它自己的两个SEPARATE内存位置吗?

mer*_*ike 5

是的,您可以通过以下方式验证:

class Student extends Person{
    public int ID;

    void foo() {
        super.ID = 1;
        ID = 2;
        System.out.println(super.ID);
        System.out.println(ID);
    }
}
Run Code Online (Sandbox Code Playgroud)


das*_*h1e 5

正确.示例中的每个类都有自己的int IDid字段.

您可以从子类中以这种方式读取或赋值:

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

或外部(当他们是公开的):

Student s = new Student();
s.ID = ... ; // to access the ID of Student
((Person) s).ID = ... ; to access the ID of Person
Run Code Online (Sandbox Code Playgroud)