就像我上面描述的标题一样。
我对如何初始化变量(例如类的实例或某些集合(如ArrayList或HashMap)有点困惑,所以我尝试了以下方法:
private MyObject someObject; // custom class
private ArrayList<String> someArrayList;
// in Constructor Method
this.someObject = null; // is it correct?
我在构造函数中做了初始化语句,但不知道是否正确。 感谢您的阅读和关心。
初始属性值可以在类构造函数中设置,因此当您创建类时,这些属性已经由您的默认值填充:
class MyObject
{
int variableOne;
int variableTwo;
// Constructor
public MyObject() {
variableOne = 5;
variableTwo = 10;
}
}
// Create the instance of class
MyObject myObject = new MyObject(); // This automatically has the values 5 and 10 in variableOne and variableTwo