非引数コンストラクターとコンパイラーの関与のみのビジネスに焦点を当てることにより、派生クラス(ChildClass
)のデフォルトコンストラクター(非引数コンストラクター)が呼び出されている間、基本クラス(ParentClass
)のサブオブジェクトがコンパイラーのヘルプのメカニズムによって作成されます(派生クラスに基本クラスのコンストラクター呼び出しを挿入します)、派生クラスのオブジェクト内にラップされます。
class Parent{
String str = "i_am_parent";
int i = 1;
Parent(){System.out.println("Parent()");}
}
class Child extends Parent{
String str = "i_am_child";
int i = 2;
Child(){System.out.println("Child()");}
void info(){
System.out.println("Child: [String:" + str +
", Int: " + i+ "]");
System.out.println("Parent: [String: ]" + super.str +
", Int: " + super.i + "]");
}
String getParentString(){ return super.str;}
int getParentInt(){ return super.i;}
public static void main(String[] args){
Child child = new Child();
System.out.println("object && subojbect");
child.info();
System.out.println("subojbect read access");
System.out.println(child.getParentString());
System.out.println(child.getParentInt());
}
}
結果:
Parent()
Child()
object && subojbect
Child: [String:i_am_child, Int: 2]
Parent: [String: ]i_am_parent, Int: 1]
subojbect read access
i_am_parent
1