摘录来自: (美)埃克尔 著 陈昊鹏 译. “java编程思想”。
那么潜在的问题是什么呢?再来看看代码:
abstract class Glypy { static int radius = 2; abstract void draw(); Glypy() { System.out.println("Glyph() before draw()"); draw(); System.out.println("Glypy() after draw()"); } } class RoundGlyph extends Glypy { int radius = 1; RoundGlyph(int r) { radius = r; System.out.println("RoundGlyph.RoundGlyph,radius= " + radius); } void draw() { System.out.println("RoundGlyph.draw(),radius=" + radius); } } public class PolyConstructors { public static void main(String[] args) { new RoundGlyph(5); } }
Glyph() before draw() RoundGlyph.draw(),radius=0 Glypy() after draw() RoundGlyph.RoundGlyph,radius= 5
总结一下:先有类而后有对象,静态方法和静态块都属于类,所以先初始化静态属性和静态块。先有父类才有子类,所以先初始化父类。
有了类就可以初始化对象了,先初始化属性然后是构造方法,再加上先父类后子类。
整个初始化可以分成两步,第一步:类初始化,父类的静态属性->父类静态块->子类静态属性->子类静态块
第二步:对象初始化,父类属性->父类构造方法->子类属性->子类构造方法
来个例子:
class Meal{ Meal(){ System.out.println("Meal"); } } class Bread{ Bread(){ System.out.println("Bread"); } } class Cheese{ Cheese(){ System.out.println("Cheese"); } } class Lettuce{ Lettuce(){ System.out.println("Lettuce"); } } class Lunch extends Meal{ static Cheese c = new Cheese(); Lunch(){ System.out.println("Lunch"); } } class PortableLunch extends Lunch{ Bread b = new Bread(); PortableLunch(){ System.out.println("PortableLunch"); } } public class Sandwich extends PortableLunch{ Lettuce l = new Lettuce(); Sandwich(){ System.out.println("Sandwich()"); } public static void main(String[] args) { new Sandwich(); } }
Cheese
Meal
Lunch
Bread
PortableLunch
Lettuce
Sandwich()