Static Member Initialization Order Among Parent, Child & Nested Classes

Viewed 45

There are parent, child and inner classes (in the child class) and respective static initializers in the below code. Normally I would expect initializers to run in the parent, child, nested class order. That holds true for initialization of outer (parent and child) member variables.

However, for the member variables of inner class itself, first its initializer of inner class and then that of the outer class are run. That seems logical but also means that assignment code in a initializer block may not be executed at the same time. For example classMemberO1 and Inner1.classMemberI1 are assigned in the same static initializer block both in outer and nested class. But value in inner block assigned to classMemberO1 whereas value in outer block is assigned to Inner2.classMemberI2. Apparently Java has a logic like "assignment resolution", but it makes language kind of scrambled. What is the mechanism behind that?

class Parent1 {
    static int classMemberP1 = 1;
    static int classMemberP2 = 2;
    static int classMemberP3 = 3;
}

class Outer1 extends Parent1 {
    static class Inner1 {
        static int classMemberI1 = 40;
        static {
            classMemberP2 = 20;
            classMemberO1 = 60;
            classMemberI1 = 41;
        }
    }
    static int classMemberO1 = 600;
    static int classMemberO2 = 700;
    static {
        classMemberP2 = 200;
        classMemberP3 = 300;
        classMemberO1 = 601;
        Inner1.classMemberI1 = 400;
        Inner2.classMemberI2 = 500;
    }
    static class Inner2 {
        static int classMemberI2 = 50;
        static {
            classMemberO2 = 70;
        }
    }

    public static void main(String[] args) {
        System.out.println("classMemberP1: " + classMemberP1);
        System.out.println("classMemberP2: " + classMemberP2);
        System.out.println("classMemberP3: " + classMemberP3);
        System.out.println("classMemberO1: " + classMemberO1);
        System.out.println("classMemberO2: " + classMemberO2);
        System.out.println("Inner1.classMemberI1: " + Inner1.classMemberI1);
        System.out.println("Inner2.classMemberI2: " + Inner2.classMemberI2);
    }
}

Result is:

classMemberP1: 1
classMemberP2: 20
classMemberP3: 300
classMemberO1: 60
classMemberO2: 70
classMemberO2: 800
Inner1.classMemberI1: 400
Inner2.classMemberI2: 500
0 Answers
Related