静态初始化器vs实例初始化器vs构造函数 [英] Static Initializers vs Instance Initializers vs Constructors
本文介绍了静态初始化器vs实例初始化器vs构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在攻读Java考试。在我学习的时候,我遇到了对我不熟悉的java语法。例如花括号({})隐藏没有名称的类主体,有些有一个static关键字。我发现他们被称为初始化器。任何人都可以帮助我指出他们之间的关键差异,以及它们如何与构造函数不同。感谢
I am studying for an exam about Java. While I was studying, I have encountered syntaxes in java which are unfamiliar to me. Such as a curly braces({}) unside a class body without a name, some has a static keyword. I have found out that they are called "Initializers". Can anyone help me point out key differences among them and how they differ from a Constructor. Thanks
推荐答案
它们之间的主要区别是它们执行的顺序。为了说明,我将用一个例子解释它们:
The main difference between them is the order they are executed. To illustrate, I will explain them with an example:
public class SomeTest {
static int staticVariable;
int instanceVariable;
// Static initialization block:
static {
System.out.println("Static initialization.");
staticVariable = 5;
}
// Instance initialization block:
{
System.out.println("Instance initialization.");
instanceVariable = 10;
}
// Constructor
public SomeTest() {
System.out.println("Constructor executed.");
}
public static void main(String[] args) {
new SomeTest();
new SomeTest();
}
}
输出将是:
Static initalization.
Instance initialization.
Constructor executed.
Instance initialization.
Constructor executed.
简要说明:
- $ b $
- 每次实例化对象时,实例初始化块都会在构造函数之前运行。
- 构造函数(显然)在每次实例化对象时运行。
- Static initialization blocks run once the class is loaded by the JVM.
- Instance initialization blocks run before the constructor each time you instantiate an object.
- Constructor (obviously) run each time you instantiate an object.
这篇关于静态初始化器vs实例初始化器vs构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文