java - '{}' 中的主类 block 从不执行

标签 java puzzle

考虑以下代码:-

class Name {

    {System.out.println("hi");}

    public static void main(String[] args) {
        System.out.println(waffle());
    }

    static boolean waffle() {
        try {
            return true;
        } finally {
            return false;
        }
    }
}

这永远不会输出 "hi"。为什么是这样?

最佳答案

大括号中的代码是instance initializer .

来自 The Java Language Specification, Third Edition , Section 8.6 :

An instance initializer declared in a class is executed when an instance of the class is created (§15.9), as specified in §8.8.5.1.

如果Name类被执行,public static void main(String[])方法被Java虚拟机调用,但是Name class is not is not is not instantiated, 因此实例初始化器中的代码将永远不会被执行。

还有一个static initializer ,它在外观上类似于实例初始化器,但它前面有 static 关键字:

static {
    // Executed when a class is first accessed.
}

同样,来自 The Java Language Specification, Third Edition , Section 8.7 :

Any static initializers declared in a class are executed when the class is initialized and, together with any field initializers (§8.3.2) for class variables, may be used to initialize the class variables of the class (§12.4).

Initializing Fields来自 The Java Tutorials 的页面还包含有关静态和实例初始化程序 block 的信息。

关于java - '{}' 中的主类 block 从不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1351397/

相关文章:

java - 是java中的类型转换还是其他什么?

java - Android 应用程序没有互联网连接时弹出窗口

java - 类型不匹配 : cannot convert from String to

用于开发益智游戏(例如 Jigsaw)的 Java 框架

algorithm - 在面板上放置随机的非重叠矩形

algorithm - 线性时间投票算法。我不明白

java - @AutoAnnotation 有什么用?怎么可以用呢?

java - 缺少来自套接字的数据

puzzle - 检查数字是否可被3整除

xcode - 带有15个拼图的图像的益智游戏(十五个游戏)