简体   繁体   English

为什么此Java程序没有显示错误?

[英]Why is this Java program showing no error?

Consider the below code, 考虑下面的代码,

I forgot to define the method name, just the code within the 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.");
    }

}

is it because blocks{} in java defines a scope? 是因为Java中的blocks {}定义了作用域?

A block {} defines the scope in Java. 块{}定义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. 许多其他计算机语言定义了2个通用范围类别:全局和局部。

What you've got there is an instance initializer , as described by section 8.6 of the JLS . 您所拥有的是一个实例初始化程序 ,如JLS的8.6节所述

It's executed before the body of any constructor when an instance is created - just like field initializers. 创建实例时,它在任何构造函数的主体之前执行-就像字段初始化程序一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM