由於JVM規範class
文件是建立這樣:
ClassFile {
u4 magic;
u2 minor_version;
u2 major_version;
u2 constant_pool_count;
cp_info constant_pool[constant_pool_count-1];
u2 access_flags;
u2 this_class;
u2 super_class;
u2 interfaces_count;
u2 interfaces[interfaces_count];
u2 fields_count;
field_info fields[fields_count];
u2 methods_count;
method_info methods[methods_count];
u2 attributes_count;
attribute_info attributes[attributes_count];
}
的super_class
領域包括:
'對於一個類中,super_class項的值必須要麼是零或必須是常量池表中的有效索引。如果super_class項的值不爲零,那麼該索引處的constant_pool條目必須是一個CONSTANT_Class_info(§4.4.1)結構,該結構表示由此類文件定義的類的直接超類。直接超類或其任何超類都不能在其ClassFile結構的access_flags項中設置ACC_FINAL標誌。
如果super_class項的值爲零,那麼這個類文件必須表示類Object,唯一沒有直接超類的類或接口。
對於接口,super_class項的值必須始終是constant_pool表中的有效索引。該指數在constant_pool條目必須是代表類CONSTANT_Class_info結構Object.`
更有趣的是fields[]
部分:
Each value in the fields table must be a field_info (§4.5) structure giving a complete description of a field in this class or interface. The fields table includes only those fields that are declared by this class or interface. It does not include items representing fields that are inherited from superclasses or superinterfaces.
所以編譯的類不包含繼承的字段。另一方面,當創建一個對象時,超級字段在內存中。爲什麼?讓我們想象一下例子:
classs A {
int a;
A(int a) {
this.a = a;
}
void methodA() {
System.out.println("A is: " + a);
}
}
classs B extends A {
int b;
B(int b) {
super(10);
this.b = b;
}
void methodB() {
super.methodA();
System.out.println("B is: " + b);
}
}
輸出應該是:A is: 10 \n B is ...
。
'private'成員不是繼承的,而是存在於父級(super)的實例化對象中。你的問題實際上是關於陰影(我認爲?你似乎在談論不適用於Java的對象的大小)。請參閱:http://stackoverflow.com/questions/3501060/can-parent-and-child-class-in-java-have-same-instance-variable –
你能否提供確切的文字說明他們沒有被遺傳?在這一點上,我認爲在術語方面存在混淆。根據Java規範,子類不會「繼承」其超類的私有成員,但是它使用非常嚴格的繼承概念,這對Java規範很有用。這個子類的實例肯定會有它自己的實例。所以,從這個意義上講,在你的問題中使用的意義,它們是繼承的。 – Nimrand
@Nimrand確切的文字是:'當一個成員被聲明爲private時,一個子類不能繼承它。'在私人成員 – Sam