How Many Ways to Create Object in Java?

How many ways to create object in Java? The answer is there are many ways but in this tutorial I am sharing the 5 ways to do this.

  1. Using new Keyword
  2. Using object cloning
  3. Using Class.forName()
  4. Using Class Loader
  5. Using Object Deserialization

Below I have discussed each of these methods one by one with example.

 

How Many Ways to Create Object in Java?

How Many Ways to Create Object in Java?

Method 1: Using new Keyword

It is most common and popular method to create object in Java.

Example:

Method 2: Using Object Cloning

We can create clone of an existing object using clone() method. The class must implement Cloneable interface. It can be done in following way.

Example:

Method 3: Using Class.forName()

Example: 

Method 4: Using Class Loader

Example: 

Method 5: Using Object Deserialization

Serialization means converting an object to byte stream to save it somewhere. Deserialization means obtaining object from its serialized form. This another way to create object. The class must implement Serializable interface.

Example: 

Comment below if you have doubts or know other ways to create object in java.

Leave a Comment

Your email address will not be published. Required fields are marked *