5 Different Ways to Create Object in Java

Hey guys in this post, we will see the 5 different ways of creating objects in java. Let’s discuss it one by one –

5 Different ways

Following are the different ways to create a java object.

Using new keyword

  • This is the most common way to create an object in java
  • By using this approach we can call any constructor we want to call
MyClass myClass = new MyClass();

Using newInstance() method of class

  • We can also use the newInstance() method of a Class class to create an object. The newInstance() calls the no-argument constructor to create the object.
  • We can create an object by newInstance() in the following way
MyClass myClass = (MyClass) Class.forName("MyClass").newInstance();

Using clone()

  • Whenever we call clone() on any object JVM actually creates a new object for us and copies all content of the previous object into it.
  • Creating an object using the clone() does not invoke any constructor
MyClass myClass = new MyClass();
MyClass temp = (MyClass) myClass.clone();

Using object deserialization

  • Object deserialization is nothing but creating an object from its serialized form
  • whenever we serialize and then deserialize an object, JVM creates a separate object
  • In deserialization, JVM doesn’t use any constructor to create the object
ObjectInputStream stream = new ObjectInputStream(anInputStream);
MyClass myClass = (MyClass) stream.readObject();

Using newInstance() of constructor class

  • Similar to the newInstance() of Class class, There is one newInstance() in the java.lang.reflect.Constructor class which we can use to create an object
  • we can also use the parameterized constructor and private constructor by using this newInstance() method
Constructor constructor = Test.class.getDeclaredConstructor();
Test obj = constructor.newInstance();

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply