只关注无参构造器的业务和编译器的参与,在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