Initialize Object in Java

In this post, we will discuss various methods to initialize object in Java.


 

1. Naive

We can simply get an instance of the class using new operator and set the values using setters provided by the class.

Java

Download   Run Code

Output:

[John, 22]

2. Constructor

When we instantiate an object with new, 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.

Java

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 this() statement.

Java

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.

Java

Download   Run Code

Output:

[John, 22]

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz