为何输出aba,我的理解是baa。求解答


    public static class child {
        public static child t1 = new child();
        {
            System.out.println("a");

        }

        static {
            System.out.println("b");
        }

        public static void main(String[] args) {
            child t2 = new child();
        }

    }

属性是最优先加载的

你写成两个类,就行了

public class ClassTest {
    public static child t1 = new child();
    public static void main(String[] args) {
        new child();
    }
}

class child {
    {
        System.out.println("a");
    }
    static {
        System.out.println("b");
    }
}

静态在内存中是独有一份的,执行顺序是一次执行的,方法掉用加载public static child t1 = new child(); 和static { System.out.println("b"); }
执行的时候先执行public static child t1 = new child();这里面只执行System.out.println("a");然后执行static { System.out.println("b"); }最有执行
System.out.println("a");

首先创建对象时,会判断当前的类有没有被加载,如果没有则会执行类加载机制,会先加载静态属性,代码块等,并首先先赋值默认初始化值,即对象为空,然后再赋值,这里静态属性是赋值的对象,对象里面只有代码块属于它,静态代码块是属于类的,所以先执行代码块的a,接着向下执行静态代码块,执行完之后执行创建new child(),只剩下一个代码块,所有最后输出是aba