在java类中如何/何时执行括号中的代码?
所以我在这里查看这个问题。人们建议您可以将代码放入 java 类中,如下所示
class myClass
{
int a;
{
//insert code here dealing with a
}
}
括号中的代码如何执行以及何时执行?我可以放在那里的内容是否有任何限制,或者它只是保留用于变量初始化?
谢谢!
So I was looking at this question here. And people were suggesting that you can put code in a java class like so
class myClass
{
int a;
{
//insert code here dealing with a
}
}
How does the code in the brackets get executed and when does it get executed? Is there any limit to what I can put there or is it just reserved for variable initialization?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
构造函数被翻译为
the constructor is translated to
这是一个实例初始化块。我建议阅读这篇文章。它在当前类中的任何构造函数执行之前以及所有超类构造函数完成之后调用。
This is an instance initialization block. I would recommend reading this article. It is called before any constructor in the current class is executed and after all super-class constructors have completed.
您可以编写一个简单的测试来检查不同块的执行顺序:
结果:
You could write a simple test to check the order of execution of different blocks:
Result:
该代码块针对每个实例执行,即它可以访问实例方法、字段等。
它在该类的构造函数层次结构执行之后但在该类的构造函数之前执行。
因此,您必须小心访问其中的数据。
示例:
如果您现在使用
new Bar("baz");
创建一个新的Bar
实例,您将看到以下输出:如您所见,此的执行顺序是:
Foo
初始化块Foo
构造函数Bar
初始化块Bar
构造函数This code block is executed per instance i.e. it has access to instance methods, fields etc.
It is executed after the constructor hierarchy of that class has been executed but before that class' constructor.
Thus you have to be careful what data you access in there.
Example:
If you now create a new
Bar
instance usingnew Bar("baz");
, you would see this output:As you can see, the execution order of this is:
Foo
initializer blockFoo
constructorBar
initializer blockBar
constructor