Just like the title I described above.
I’m a little confused about how to initialize variables such as an instance of a class or some collections like ArrayList or HashMap, so I tried something below:
private MyObject someObject; // custom class
private ArrayList<String> someArrayList;
// in Constructor Method
this.someObject = null; // is it correct?
I made an initialization statement in the Constructor, but I don’t know if it is right.
Thanks for your reading and concern.
>Solution :
Initial property values can be set within a class constructor so when you create the class, those properties are already filled up by your default values:
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
Also note some suggestions in the comments have static infront of fields that can be instantly initialized without a constructor. However, there can be an issue if there are multiple instances of the same class, all those static variables are shared amongst all the object. This is good only in very special scenarios.