“{}”中的主类块从不执行
考虑以下代码:-
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”。这是为什么呢?
Consider the following code:-
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;
}
}
}
This never outputs "hi" . Why is this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
大括号中的代码是 实例初始值设定项。
来自 Java 语言规范,第三版,< a href="http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.6" rel="nofollow noreferrer">第 8.6 节:
如果执行
Name
类,Java虚拟机会调用public static void main(String[])
方法,但是Name
类不是未实例化的,因此实例初始化程序中的代码永远不会被执行。还有一个 静态初始化程序,外观与实例初始值设定项类似,但前面有
static
关键字:同样,来自 Java 语言规范,第三版,第 8.7 节:
初始化字段页面来自 Java 教程 还包含有关静态和实例初始值设定项块的信息。
The code in the braces is the instance initializer.
From The Java Language Specification, Third Edition, Section 8.6:
If the
Name
class is executed, thepublic static void main(String[])
method is called by the Java virtual machine, but theName
class is not is not instantiated, so the code in the instance initializer will never be executed.There is also a static initializer, which is similar in appearance to the instance initializer, but it has the
static
keyword in front:Again, from The Java Language Specification, Third Edition, Section 8.7:
The Initializing Fields page from The Java Tutorials also has information about the static and instance initializer blocks.
我认为它仅在实例创建时激活。尝试将其作为 static { ... } 运行
I think it is activated only on instance creation. Try running it as static { ... }
该块应该声明为 static 才能运行,即 static{System.out.println("hi");}
The block should be declared static to get it to run, i.e. static{System.out.println("hi");}