- publicclassSuperClass
- {
- publicStringstr="super";
- publicSuperClass(){
- update();
- }
-
- publicvoidupdate()
- {
- //TODOAuto-generatedmethodstub
- System.out.println("updateinsuper "+str);
- }
- }
- publicclassExtendingClassextendsSuperClass
- {
- publicStringstr="child";
- /**
- *方法说明:
- *@paramargs
- */
- publicstaticvoidmain(String[]args)
- {
- ExtendingClassinstance=newExtendingClass();
- }
-
- @Override
- publicvoidupdate()
- {
- System.out.println("updateinchild "+str);
- }
-
- publicExtendingClass()
- {
- super();
- update();
- //TODOAuto-generatedconstructorstub
- }
-
- }
- 最后的运行结果为:
- update in child null
update in child child - ///////////////////////
- 先为其父类及自己的属性分配内存(When an object is created, memory is allocated for all its fields, including those inherited from superclasses, and those fields are set to default initial values for their respective types (zero for all numeric types, false for boolean, '\u0000'char, and null for object references).)
- 然后调用其父类的构造函数(Invoke a superclass's constructor.),此处还没有开始执行,仅仅是调用而已。
- 初始化父类的属性和所有初始化模块(Initialize the fields using their initializers and any initialization blocks.)
- 执行父类的构造函数(Execute the body of the constructor.),结束后返回至子类的构造函数
- 初始化子类的属性和所有初始化模块(Initialize the fields using their initializers and any initialization blocks.)
- 执行子类的构造函数(Execute the body of the constructor.)
本文通过一个Java子类继承父类的例子,详细解析了对象创建过程中的内存分配、父类构造函数调用、属性初始化等关键步骤,并展示了不同构造函数中方法覆盖的效果。
364

被折叠的 条评论
为什么被折叠?



