Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I create an empty instance of class in java or how should I initialize it?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading