哪个新的是首先执行 - 在构造函数还是输出? [英] Which new is execute first -- in constructor or out?
本文介绍了哪个新的是首先执行 - 在构造函数还是输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我定义类如下:
public class myClass {
private x = new anotherClass();
private y;
public myClass() {
y = new anotherClass();
}
}
哪个变量会更早得到实例? x或y?
which variable will get instance earlier? x or y?
而且,在构造函数之外分配一个变量是不推荐的吗?
And, is it unrecommended to assign a variable outside the constructor?
推荐答案
执行顺序为:
- 超类构造函数(或同一类的链接构造函数)
- 实例变量初始化程序(在代码中分配给
x
) - 构造函数主体(代码中分配给
y
的语句)
- Superclass constructor (or chained constructor to the same class)
- Instance variable initializers (the expression assigning to
x
in your code) - Constructor body (the statement assigning to
y
in your code)
Java语言规范第12.5节包含详细信息。
是否在构造函数中分配变量取决于你 - 我非常喜欢一个经验法则,如果初始值不不依赖于任何构造函数参数,并且始终对于所有构造函数都是相同的,使用变量初始值。否则,在构造函数中分配它。
Whether you assign the variable in the constructor or not is up to you - I quite like a rule of thumb whereby if the initial value doesn't depend on any constructor parameters, and will always be the same for all constructors, use a variable initializer. Otherwise, assign it in a constructor.
这篇关于哪个新的是首先执行 - 在构造函数还是输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文