转:JAVA初始化顺序

package com.test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test extends Parent {
    private static String str = "子类静态属性3";
    static {
        Parent.println(str);
        Parent.println("子类静态块4");
    }

    private String string = "子类属性10";
    {
        Parent.println(string);
        Parent.println("子类块11");
    }

    private boolean result = true;

    public Test() {
        super();
        Parent.println("子类构造器12");
    }

    public String getSubString() {
        return !result ? "子类属性默认值6" : string;
    }

    public static void main(String[] args) {
        System.out.println("子类Main方法");
        new Test();
    }
}

class Parent {
    static private Pattern pattern = Pattern.compile("(\\D+)(\\d+)");

    static private int count = 0;

    private static String str = "父类静态属性1";
    static {
        Parent.println(str);
        Parent.println("父类静态块2");
    }
    {
        Parent.println(getParentString());
        Parent.println(getSubString());
    }

    private String string = "父类属性7";
    {
        Parent.println(string);
        Parent.println("父类块8");
    }

    private boolean result = true;

    public Parent() {
        super();
        Parent.println("父类构造器9");
    }

    public String getSubString() {
        return null;
    }

    public String getParentString() {
        return !result ? "父类属性默认值5" : string;
    }

    public static void println(String out) {
        Matcher matcher = pattern.matcher(out);
        if (matcher.find()) {
            System.out.println(String.format("%02d、%7s %02d", ++count,
                    matcher.group(1), Integer.valueOf(matcher.group(2)))
                    .replaceAll(" ", "     "));
        }
    }
}

 

输出结果:

01、     父类静态属性     01
02、          父类静态块     02
03、     子类静态属性     03
04、          子类静态块     04
子类Main方法
05、父类属性默认值     05
06、子类属性默认值     06
07、               父类属性     07
08、                    父类块     08
09、          父类构造器     09
10、               子类属性     10
11、                    子类块     11
12、          子类构造器     12

你可能感兴趣的:(java)