哪个 new 首先执行——在构造函数中还是在构造函数外?
如果我定义一个如下所示的类:
public class myClass { private x = new anotherClass(); private y; public myClass() { y = new anotherClass(); } }
哪个变量会更早获得实例? x 或 y?
而且,是否不建议在构造函数之外分配变量?
If I define a class like following:
public class myClass { private x = new anotherClass(); private y; public myClass() { y = new anotherClass(); } }
which variable will get instance earlier? x or y?
And, is it unrecommended to assign a variable outside the constructor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
执行顺序是:
x
的表达式)y
的语句) code> 在您的代码中)Java 语言规范的第 12.5 节 包含详细信息。
是否在构造函数中分配变量取决于您 - 我非常喜欢一条经验法则,即如果初始值不依赖于任何构造函数参数,并且总是 所有构造函数,都使用变量初始值设定项。否则,在构造函数中分配它。
The order of execution is:
x
in your code)y
in your code)Section 12.5 of the Java Language Specification contains the details.
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.
代码中的变量没有类型,但在调用构造函数之前首先实例化 x。 (在构造函数上对
x
进行空检查以找出答案)。至于推荐,就看你的了。有一件事,例如在JavaBeans中,由于我通常不编写默认的公共构造函数(不带参数),所以我倾向于在声明时初始化一些字段(如果需要它们不为空)。否则,我在构造函数上实例化它们。
Your variables in your code has no types, but
x
is instantiated first before the constructor is called. (Do a null check forx
on constructor to find out).As for recommendation, it's up to you. One thing, e.g. in JavaBeans, since I usually don't write a default public constructor (with no arguments), I tend to initialize some fields on declaration (if they are needed to be not null). Otherwise, I instantiate them on constructor.
我建议您进行测试,而不是仅仅从其他人那里得到答案:
让
anotherClass
的构造函数打印传递过来的字符串。然后你可以告诉我们!
I recommend you test, instead of just getting an answer from someone else:
Make the constructor of
anotherClass
print the string passed through.And then you can tell us!