package com.cwcec.test; class Fu { int num = 5; //构造代码块 { System.out.println("Fu constructor code..." + num); num=6; } public Fu() { System.out.println("Fu constructor ..." + num); show(); } void show() { System.out.println("show ..." + num); } } class Zi extends Fu { int num = 9; //构造代码块 { System.out.println("Zi constructor code..." + num); num = 10; } public Zi() { System.out.println("Zi constructor ..." + num); } void show() { System.out.println("show ..." + num); } } public class FieldDemo { public static void main(String[] args) { new Zi(); } }
Output:
Fu constructor code...5
Fu constructor ...6
show ...0
Zi constructor code...9
Zi constructor ...10
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Animal { public String name = "Ti"; public static int age = 10; static { System.out.println("Animal age : " + age); } public Animal() { age = 100; System.out.println("Animal constructor..."); } public void display() { System.out.println("name: " + name); } } class Dog extends Animal { public static int size = 20; static { System.out.println("Dog size : " + size); } public Dog() { size = 200; System.out.println("Dog constructor..."); } public static void sleep() { System.out.println("Dog sleep..."); } } public class Single { public static void main(String[] args) { Dog dog = new Dog(); } }
总结
1.执行的大致顺序如下,
(1) 在一个不存在继承的类中:初始化static变量,执行static初始化快-->初始化普通成员变量(如果有赋值语句),执行普通初始化块-->构造方法
(2)在一个存在继承的类中:初始化父类static成员变量,运行父类static初始化块-->初始化子类static成员变量,运行子类static初始化块-->初始化父类实例成员变量(如果有赋值语句),执行父类普通初始化块-->父类构造方法-->初始化子类实例成员变量(如果有赋值语句)及普通初始化块-->子类构造方法。