如何在java中创建类的空实例或者如何初始化它?

问题描述 投票:0回答:1

就像我上面描述的标题一样。

我对如何初始化变量(例如类的实例或某些集合(如ArrayListHashMap)有点困惑,所以我尝试了以下方法:

private MyObject someObject; // custom class
private ArrayList<String> someArrayList;

// in Constructor Method
this.someObject = null; // is it correct?

我在构造函数中做了初始化语句,但不知道是否正确。 感谢您的阅读和关心。

java initialization
1个回答
0
投票

初始属性值可以在类构造函数中设置,因此当您创建类时,这些属性已经由您的默认值填充:

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
© www.soinside.com 2019 - 2024. All rights reserved.