我是Java的新手.任何人都可以解释主方法中发生了什么?
class Demo {
public static void main(String []args) {
//setting a name using the constructor
Thread t=new Thread("main"){
//what is this? a static block?? need an explanation to this.
{setName("DemoThread");}
};
//output is DemoThread. Since it set the name again.
System.out.println(t.getName());
}
}
Run Code Online (Sandbox Code Playgroud)
这一行:
{setName("DemoThread");}
Run Code Online (Sandbox Code Playgroud)
被称为初始化块(或实例初始化块).它看起来像一个静态初始化程序块,但没有static关键字.它对匿名类很有用,因为它们不能有命名构造函数.更多细节可以在这里找到.