在构造函数中实例化对象 [英] Instantiating object in a constructor
问题描述
以下代码的结果似乎相同,所以我应该何时使用?
It seems that the result of the following code is the same, so when should I use each?
public class Person {
public Person() {
this.family = new Family();
}
Family family;
}
到
public class Person {
Family family = new Family();
}
(我能想到的一个场景是,当我有多个构造函数时,我们想要仅在其中一个内部创建一个家庭实例...是唯一的情况吗?)
(one scenario I can think of, is when having multiple constructors and we want to create an instance of family only inside one of them... is that the only case?)
推荐答案
对于类变量 [静态变量]你不能使用第一个,因为你希望初始化只发生一次,而不是每次你调用你的构造函数。
For class variables [static variable] you cannot use the first, since you want the initializtion to happen only once, and not with every time you invoke your constructor.
例如变量,第二个只是第一个的合成糖。
有时你可能必须使用第二个 - for参数构造函数,它们本身 - 传递给你的构造函数。
For instance variables, the second is just a syntatic sugar of the first.
Sometimes you might have to use the second - for argument constructor, which are themselves - passed to your constructor.
这篇关于在构造函数中实例化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!