Java域隐藏

3
在以下情景中:
class Person{
    public int ID;  
}

class Student extends Person{
    public int ID;
}

学生“隐藏了人的ID字段。

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

Student john = new Student();

约翰的对象是否有两个单独的内存位置来存储Person.ID和自己的内容?

3个回答

5

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

class Student extends Person{
    public int ID;

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

5

正确。在你的例子中,每个类都有自己的int ID id字段。

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

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

或者在外部(当它们是公共的时候):
Student s = new Student();
s.ID = ... ; // to access the ID of Student
((Person) s).ID = ... ; to access the ID of Person

这与我下面的注释相对应:这意味着"Person"在内存中占用8个字节的空间,并具有两个存储着两个ID的内存位置,是吗? - Bober02

1

是的,这是正确的。将有两个不同的int。

您可以通过以下方式访问 Student 中的 Person 的int:

super.ID;

请注意,成员变量不会发生动态调度。如果您在Person上定义使用ID字段的方法,则该方法将引用Person的字段,而不是Student的字段,即使在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();
    }
}

以上代码将输出42,而不是1。

为了确保,内存应该像这样:120: 10 -> Person.ID 124: 99 -> this.ID但是新的Student()只有120: 10 - Bober02
我不明白你的评论。学生有它自己的ID,并且还有一个与之相同名称的第二个独立的int,从Person继承而来。这两个int并不共享相同的内存位置,可以独立访问。(是否实际使用这个“特性”是值得争议的。这可能非常令人困惑,尤其是在虚方法中。) - Mat
好的,我想问的是新实例化的学生对象是否占用了8个字节的内存(两个不同的内存位置对应两个ID),而学生只占用了4个字节的内存? - Bober02
我还是不明白,你的评论有自相矛盾之处。当你创建一个学生时,你实例化(或多或少)它的所有类层次结构。因此,你将使用至少两个 int 值的存储空间,一个用于 Person 中的 ID,另一个用于 Student 中的 ID。 - Mat
这就是我的意思,一个学生的ID :) 和一个人的ID :)。 - Bober02

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接