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?

You May Also Like:

Why should I choose Java for Software Development? What are Pros and Cons of Java?
Can we cast an int value into byte type variable? what if the value of int is larger than byte?
Can We store a double value in a long type variable without casting?
Why Java is not 100% Object-oriented language?
What are the differences between 32-bit and 64-bit versions of Java?
Can we call static method with null object?
Can we override static method in Java?
What will be the output of following java program?
What is the difference Between java.util.Date and java.sql.Date in Java ?
What is difference between using Serializable & Externalizable Interfaces in Java?
Which Java data type would you choose for storing sensitive information, like passwords, and Why?
What is left shift << and Unsigned right shift >>> operator in Java? How are these useful?

If you have any feedback or suggestion please feel free to drop in below comment box. 

Leave a Reply

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