在以下情形:Java字段隐藏
class Person{
public int ID;
}
class Student extends Person{
public int ID;
}
学生“隐藏的人ID字段
如果我们想代表在内存中的以下内容:
Student john = new Student();
将约翰对象有两个独立的存储位置,用于storint Person.ID和它自己的?
在以下情形:Java字段隐藏
class Person{
public int ID;
}
class Student extends Person{
public int ID;
}
学生“隐藏的人ID字段
如果我们想代表在内存中的以下内容:
Student john = new Student();
将约翰对象有两个独立的存储位置,用于storint Person.ID和它自己的?
正确的。您示例中的每个班级都有自己的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
的int类型Student
有:
super.ID;
不过要小心,动态调度不发生对成员字段。如果您在使用ID
字段的Person上定义方法,则即使在Student
对象上调用该字段,它也会引用Person
的字段,而不是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
是的,你可以验证:
class Student extends Person{
public int ID;
void foo() {
super.ID = 1;
ID = 2;
System.out.println(super.ID);
System.out.println(ID);
}
}
这对应于我的评论如下:这意味着人,在内存中占用8个字节的空间,并有两个存储位置持有两个ID对? – Bober02
是的,你有两个ID – dash1e