初始化的顺序

一个例子解释所有的初始化问题。

public class Solution {
    public static class Base {
        {
            display("1, at Base static block 1");
            displayFinal("2, at Base static block 1");
            f = getInitValue("3, at Base static block 1", 11);
        }

        int f = getInitValue("4, at Base declearation", 22);

        {
            display("5, at Base static block 2");
            displayFinal("6, at Base static block 2");
            f = getInitValue("7, at Base static block 2", 33);
        }

        public Base() {
            System.out.println("8, Entry Base construstor");
            f = 44;
            display("9, at Base construstor");
            displayFinal("10, at Base construstor");
        }

        protected void display(String msg) {
            System.out.println("99, Entry Base display()");
            System.out.println(msg + " Base.f: " + f);
        }

        protected final void displayFinal(String msg) {
            System.out.println(msg + " Base.f: " + f);
        }


        public static class Derived extends Base {
            {
                display("11, at Derived static block 1");
                f = getInitValue("12, at Derived Base static block 1", 111);
            }

            int f = getInitValue("13, at Derived declearation", 222);

            {
                display("14, at Derived static block 2");
                f = getInitValue("15, at Derived static block2", 333);
            }

            public Derived() {
                System.out.println("16, Enter Derived construstor");
                f = 444;
                display("17, at Derived construstor");
            }

            @Override
            protected void display(String msg) {
                System.out.println("18, Enter Derived.display()");
                System.out.println(msg + " Derived.f: " + f);
            }
        }

        public static int getInitValue(String msg, int value) {
            System.out.println(msg + " assiging");
            return value;
        }

        public static void main(String[] args) {
            new Derived();
        }
    }
}