think in java 第5章 完整的JAVA初始化规则
package think.in.exercise11; /** * @author Administrator * 完整展示JAVA的初始化顺序 * 1:递归寻找顶层基类 * 2:静态成员初始化 * 3:静态块初始化 * 4:成员变量按先后顺序初始化 * 5:顶层基类的构造方法主体 * 6:下层子类的构造,重复2~6的执行步骤 */ class Meal{ private String first = getFirst(); private String second = getSecond(); private static String zero = getZero();//静态成员放在前的成员后面,但最先执行 public Meal(){ System.out.println("4:Meal()基类构造方法调用"); } static{//静态块 System.out.println("3:Meal()基类静态块初始化"); } private static String getZero(){ System.out.println("0:静态成员变量最先初始化"); return "zero"; } private String getFirst(){ System.out.println("1:按顺序初始化非静态成员变量 first"); return "first"; } private String getSecond(){ System.out.println("2:按顺序初始化非静态成员变量 second"); return "second"; } } class Bread{ public Bread(){ System.out.println("Bread()"); } } class Cheese{ public Cheese(){ System.out.println("Cheese()"); } } class Lettuce{ public Lettuce(){ System.out.println("Lettuce()"); } } class Lunch extends Meal{ public Lunch(){ System.out.println("Lunch()"); } } class PortableLunch extends Lunch{ public PortableLunch(){ System.out.println("PortableLunch()"); } } public class Sandwich extends PortableLunch{ private Bread b = new Bread(); private Cheese c = new Cheese(); private Lettuce l = new Lettuce(); public Sandwich(){ System.out.println("Sandwich()"); } public static void main(String[] args) { // TODO Auto-generated method stub new Sandwich(); } }