1.本例子借用thinkingInJava第4版中文版P163中PolyConstructors.java例子修改后,说明一定问题:
该类中包含:静态属性、静态代码块、成员变量、普通代码块、父子类关系、子类重写父类方法
package com.iteye.bobby.base; import static net.mindview.util.Print.*; class Glyph { private static String baseStr = "static String field"; static { System.out.println("baseStr = " + baseStr); System.out.println("Glyph.enclosing_method(static)"); } { System.out.println("Glyph.enclosing_method(noraml)"); } Glyph() { print("Glyph() before draw()"); draw(); print("Glyph() after draw()"); } void draw() { print("Glyph.draw()"); } } class RoundGlyph extends Glyph { private int radius = 1; private Glyph glyph = new Glyph();//成员变量赋值时创建对象 static { System.out.println("RoundGlyph.enclosing_method(static)"); } { System.out.println("RoundGlyph.enclosing_method(noraml)"); System.out.println(" radius = " + radius); System.out.println("new glyph() = " + glyph); } RoundGlyph(int r) { radius = r; print("RoundGlyph.RoundGlyph(), radius = " + radius); } void draw() { print("RoundGlyph.draw(), radius = " + radius); } } public class PolyConstructors { public static void main(String[] args) { new RoundGlyph(5); } }
Result:
baseStr = static String field
Glyph.enclosing_method(static)
RoundGlyph.enclosing_method(static)
Glyph.enclosing_method(noraml)
Glyph() before draw()
RoundGlyph.draw(), radius = 0
Glyph() after draw()
Glyph.enclosing_method(noraml)
Glyph() before draw()
Glyph.draw()
Glyph() after draw()
RoundGlyph.enclosing_method(noraml)
radius = 1
new glyph() = com.iteye.bobby.base.Glyph@61de33
RoundGlyph.RoundGlyph(), radius = 5
2.总结类的初始化顺序
1)类的初始化
a.初始化类属性、初始化类静态代码块(先父后子,按书写顺序执行)
2)对象的创建
a.所有的成员变量—包括该类,及它的父类中的成员变量--被分配内存空间,并赋予默认值。
b.为父类的成员变量赋值,并执行父类的普通代码块(按书写顺序执行)
c.执行父类构造函数
d.为子类的成员变量赋值,并执行子类普通的代码块(如果成员变量赋值时创建对象,则先父后子执行普通代码块和构造方法,然后在往下走)
e.执行子类构造函数