What are all the different ways to create an object in Java

What are all the different ways to create an object in Java? This is one of popular questions in any Java Core interview. We all know how to create objects of any class by using new keyword. However, We will find out all the different ways to create an object in Java.

What are all the different ways to create an object in Java

I will list down all other ways as i know:

  • Using new keyword
  • Using Class.forName()
  • Using clone()
  • Deserialization
  • Using reflection
  • ClassLoader loadClass()

We will see the syntax of all the above ways

Using New keyword

This is the most common way to create an object in java. Almost of objects are created in this way.

MyClass object = new MyClass();

Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.

MyClass object = (MyClass) Class.forName(“mypackage.MyClass”).newInstance();

Class.forName() loads the class in memory. To create an instance of this class, we need to use newInstance().

Using clone() of java.lang.Object
The clone() can be used to create a copy of an existing object.

MyClass myObject = new MyClass();
MyClass myObject2= (MyClass) myObject .clone();

Using Object deserialization

Object deserialization is also a way to have another instance of a class.

ObjectInputStream objStream = new ObjectInputStream(inputStream);
MyClass obj = (MyClass) inStream.readObject();

Using Reflection

This is also a popular way to create new instances in most of available frameworks.

myConstructor.newInstance();
or
MyClass.newInstance();

Using class loader’s loadClass()

Using class loader’s loadClass() method but this is not often used.

myInstance.getClass().getClassLoader().loadClass(“MyClass”).newInstance();

That’s it on the question What are all the different ways to create an object in Java?

2 thoughts on “What are all the different ways to create an object in Java

    • Hi VIKASH KUMAR, you’re right. However, factory Method is just a pattern for getting objects. And it uses internally “new” keyword for creating objects. It is the reason why factory method is not mentioned here

Leave a Comment

*

Please share it if you found this useful
Hide Buttons