gpt4 book ai didi

java - 为什么这个 Java 程序没有显示错误?

转载 作者:行者123 更新时间:2023-11-29 03:16:35 25 4
gpt4 key购买 nike

考虑下面的代码,

我忘了定义方法名,只是 block 中的代码。

public class Demo {

{
Apple ap;
// Display price of Winesap.
System.out.println("Winesap costs " + Apple.Winesap.getPrice()
+ " cents.\n");
// Display all apples and prices.
System.out.println("All apple prices:");
for (Apple a : Apple.values())
System.out.println(a + " costs " + a.getPrice() + " cents.");
}

}

是不是因为java中的blocks{}定义了作用域?

A block {} defines the scope in Java. Each time you start a new block, you are creating a new scope. A scope determines what objects are visible to other parts of the program. It also determines the lifetime of these objects. Many other computer languages define 2 general category of scopes : global and local.

最佳答案

section 8.6 of the JLS 所述,您得到的是一个实例初始化器 .

它在创建实例时在任何构造函数的主体之前执行 - 就像字段初始值设定项一样。

关于java - 为什么这个 Java 程序没有显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26230456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com