How many ways we can create an object in Java?

By | August 25, 2019

In this blog post we will talk  about How many ways we can create an object in Java? We see there are 6 different ways to create an Object in Java.

Method-1

We can create an Object using new keyword. This is the most common way to create an object in java and almost 99% of objects are created in this way.
Example: MyClass object1 = new MyClass();

 Method-2

We can dynamically load Class using Class.forName(“Qualified Name of Class”) in refection after that we can make use of newIntance() method to create an Object of provided “Qualified Name of Class”)

Loading class dynamically
Class cls = Class.forName(“kkjavatutorials.com.MyClass”);
MyClass object2 = (MyClass)cls. .newInstance();

Above two lines, we can write in Single line as below
MyClass object2 = (MyClass) Class.forName(“kkjavatutorials.com.MyClass”).newInstance();

Method-3

We can use Object’s class clone() method  to create a copy of an existing object.

MyClass secondObject = new MyClass();
MyClass object3 = (MyClass) secondObject.clone();

Method-4

We can create an Object using ClassLoader as below
Object object4 = MyClass.class.getClassLoader().loadClass(“kkjavatutorials.com.MyClass”).newInstance();

Method-5

We can use the Constructor class from the java.lang.reflect

Class<MyClass> class1 = MyClass.class;
Constructor<?> constructor = class1.getDeclaredConstructors()[0];
MyClass object5 = (MyClass) constructor.newInstance();

Method-6

We can create Object using  Deserialization process.  Deserialization process is nothing but creating an object from its serialized form.

Now Let’s create an Example where we will see all the above 6 methods to create an object

Sample output 

That’s all about  How many ways we can create an object in Java?
If you have any feedback or suggestion please feel free to drop in blow comment box. 

Leave a Reply

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