This post will discuss various methods to initialize an object in Java.

1. Naive method

The idea is to get an instance of the class using the new operator and set the values using the class setters.

Download  Run Code

Output:

[John, 22]

2. Constructor

When we instantiate an object with a new operator, we must specify a constructor. A constructor has the same name as the class and no return type. It can accept a set of parameters, which are the fields we want to set values for, or it can be parameter-less (no-arg constructor). If we declare a class with no constructors, the compiler will automatically create one for the class.

Download  Run Code

Output:

[John, 22]

3. Copy Constructor

A copy constructor is a special constructor for creating a new object as a copy of an existing object. It takes just one argument that will be another instance of the same class. We can explicitly invoke another constructor from the copy constructor by using the this() statement.

Download  Run Code

Output:

[John, 22]

4. Anonymous Inner Class

Another alternative to initialize an object is to use “Double Brace Initialization”. This creates an anonymous inner class with just an instance initializer in it. The use of this method is highly discouraged.

Download  Run Code

Output:

[John, 22]

That’s all about initializing an object in Java.