首页 > 解决方案 > 谁能解释一下为什么两个代码都按此顺序打印输出的原因(静态关键字执行优先级)

问题描述

代码 1:

    public class test {
        static {System.out.println("I am here in static");}
        public test()
        {
            System.out.println("I am here in constructor");
        }
    
        public static void main(String[] args)
        {
            System.out.println("I am here in Main");
            test staticCheck=new test();
        }

输出 1:我在这里是静态的 我在这里是 Main 我在这里是在构造函数中

代码 2:

    public class test {
        {System.out.println("I am here in static");}
        public test()
        {
            System.out.println("I am here in constructor");
        }
    
        public static void main(String[] args)
        {
            System.out.println("I am here in Main");
            test staticCheck=new test();
    
        }
    
    }

输出 2:我在 Main 我在静态我在这里我在构造函数

标签: javastaticstatic-methods

解决方案


因为写 CODE 2 的人都是骗子。

CODE 2 中的“我在静态中”应该改为“我在实例初始化块中”。每次初始化实例时,IIB 都会在构造函数之前运行。

在本教程中查看更多信息。


推荐阅读