java - 谁能解释为什么这两个代码都按此顺序打印输出的原因(静态关键字执行优先级)

标签 java static static-methods

代码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: 我在这里静态 我在主这里 我在构造函数中

代码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: 我在主这里 我在这里静态 我在构造函数中

最佳答案

因为编写代码 2 的人都是骗子。

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

查看更多this tutorial .

关于java - 谁能解释为什么这两个代码都按此顺序打印输出的原因(静态关键字执行优先级),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66794047/

相关文章:

C# - 静态方法中的参数线程安全吗?

java - 为什么将静态方法视为方法?

c++ - 编译错误 - 静态成员

java - Jetty 将错误的 NIO 参数传递给 Java(或 JVM 错误)

java - 正则表达式中的字边界

java - 静态同步方法与所有代码都在同步块(synchronized block)中的静态方法

c# - .NET 公共(public)静态变量的 "lifespan"?

java - svn 导致 eclipse 中的构建错误

java - JClouds:BlobStore.getBlob() 需要很长时间

java - 为什么我不能以这种方式在静态方法中返回任何内容