Java为什么静态打印出文本而不是方法 [英] Java why static prints out text first than method
问题描述
只是想知道为什么静态总是首先打印而不是方法。
Just wondering why static is always the one that will print out first rather than a method.
代码:
public class TestMe {
static {
System.out.println("D");
}
{
System.out.println("B");
}
public void printMe() {
System.out.println("Z");
}
public static void main(String []args) {
new TestMe().printMe();
}
}
输出:
D
B
Z
推荐答案
您的班级中有两种类型的初始化程序块
You have two types of initializer block in your class
一个是静态初始化程序
在初始化类时执行
one is static initializer
which is executed by the time the class is initialized
A static initializer declared in a class is executed when the class is initialized
两个是实例初始值设定项
,当类的实例已经创建时执行
two is the Instance Initializers
which is executed when instance of the class is already create
An instance initializer declared in a class is executed when an instance of the class is created
这些来自 JLS文档
所以静态初始化程序$ c初始化类时将直接调用$ c>与已创建该类的实例时调用的
实例初始化程序
因此静态初始化程序$首先执行c $ c>。
So static initializer
will be called directly when class is initialized vs Instance Initializers
that is called when instance of that class is already created thus static initializer
is executed first.
这篇关于Java为什么静态打印出文本而不是方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!