Various ways to create Object in Java – 4 ways

In this article, we will discuss various ways to create Object in Java i.e.;

Various ways to create Object in Java

Primarily, there are only 4 ways to create object in Java, those are;

  • Using new operator or keyword
  • Using clone method of Object class
  • Using Object De-serialization
  • Using Reflection API

But using reflection way, we can derive multiple ways to create objects in Java

 

Let us move forward and discuss all possible ways to create object in Java

Way 1: Using new operator or keyword

This is very common way to create or instantiate new objects, as shown in the below demo example

UsingNewOperatorOrKeyword.java

package in.bench.resources.various.ways.to.create.objects;

public class UsingNewOperatorOrKeyword {

	public static void main(String[] args) {

		// Way 1: using new operator or keyword
		UsingNewOperatorOrKeyword object1 = new UsingNewOperatorOrKeyword();
	}
}

 

Way 2: Using clone() method of Object class

clone() method of Object class, creates another copy of the same Object with all its details

Method signature :

protected native Object clone() throws CloneNotSupportedException;

 

UsingCloneMethodOfObjectClass.java

package in.bench.resources.various.ways.to.create.objects;

public class UsingCloneMethodOfObjectClass implements Cloneable {

	public static void main(String[] args) {

		// normal way of creating / instantiating new object
		UsingCloneMethodOfObjectClass ucmooc = new UsingCloneMethodOfObjectClass();

		try {
			// Way 2: using clone() method of Object class
			UsingCloneMethodOfObjectClass object2 = (UsingCloneMethodOfObjectClass) ucmooc.clone();

			// invoking display() method
			object2.display();
		} 
		catch (CloneNotSupportedException cnsex) {
			cnsex.printStackTrace();
		}
	}

	// display() method to test
	public void display() {
		System.out.println("display() method is invoked");
	}
}

Output:

display() method

 

Thinks to consider while creating Object using clone method:

  1. The class for which cloning is performed, it must implement ”java.lang.Cloneable” interface, otherwise “java.lang.CloneNotSupportedException” will be thrown
  2. Explicit type-cast is required, as shown in the below figure point-1.
  3. It is necessary to handle compile-time exception either by throws clause or surrounding with try-catch block, as shown in the below figure point-2.

 

Way 3: Using Object de-serialization process

This case, assumes that already object is serialized using serialization process. Now, when reverse process happens i.e.; de-serializing binary file format from file storage into Java’s heap memory, then a new Object is created

UsingDeSerialization.java

package in.bench.resources.various.ways.to.create.objects;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

import in.bench.resources.serialize.deserialize.arraylist.Customer;

public class UsingDeSerialization {

	public static void main(String[] args) {

		// creating input stream variables
		FileInputStream fis = null;
		ObjectInputStream ois = null;

		// to hold customer values after de-serialization 
		Customer customer = null;
		try {
			// reading binary data
			fis = new FileInputStream("Customer.ser");

			// converting binary-data to java-object
			ois = new ObjectInputStream(fis);

			// Way 3: creating Object after de-serialization
			customer = (Customer) ois.readObject();
		} 
		catch (FileNotFoundException fnfex) {
			fnfex.printStackTrace();
		}
		catch (IOException ioex) {
			ioex.printStackTrace();
		} 
		catch (ClassNotFoundException ccex) {
			ccex.printStackTrace();
		}

		System.out.println("Customer values : " + customer);
	}
}

Explanation:

  • Assume that, already Customer object is serialized in the file named “Customer.ser”
  • Above program depicts the steps to de-serialize an Object (i.e.; de-serializing from file storage in binary format into Java’s heap memory)
  • Notice line no. 28, which read object’s state and re-creates a new object
  • In this way, a new Object can be created in Java using Object de-serialization process

 

Way 4: Using Reflection & newInstance() method of Class & Constructor

There are different variants while dealing with reflection way of creating objects i.e.;

Using Classes & Constructors:

  1. Using Class.forName(“fully.qualified.name.of.class”).newInstance();
  2. Using <ClassName>.class.newInstance();
  3. Using <ClassName>.class.getClassLoader().loadClass(“fully.qualified.name.of.class”).newInstance();
  4. Using Constructor i.e.;
    Constructor<<className>> constructor = <ClassName>.class.getConstructor();
    <ClassName> object44 = constructor.newInstance();

 

Pre-requisite:

To create Object using reflection & newInstance() method way, we require below 2 things in advance

  • Fully qualified class name
  • default public constructor, because newInstance() method invokes default no-arg constructor while creating Object

 

Way 4.1: Reflection – Class.forName(“className”).newInstance();

This type of Object creation is commonly encountered while connecting database at a lower level i.e.; for loading & creating Object of that particular driver type

Loading –> Class.forName(“fully.qualified.class.name”)
Creating –> invoking newInstance() method on that particular loaded class

For example,

  • Oracle –> oracle.jdbc.driver.OracleDriver
  • MySQL –> com.mysql.jdbc.Driver
  • SQL Server –> com.microsoft.sqlserver.jdbc.SQLServerDriver
  • MS Access –> sun.jdbc.odbc.JdbcOdbcDriver

 

UsingClassForNameOfReflection.java

package in.bench.resources.reflection;

public class UsingClassForNameOfReflection {

	// public no-arg constructor
	public UsingClassForNameOfReflection() {
		System.out.println("newInstance() method invokes: default no-arg constructor");
	}

	public static void main(String[] args) {

		try {
			// Way 4.1: using Class.forName("className").newInstance()
			UsingClassForNameOfReflection object41 = 
					(UsingClassForNameOfReflection) Class
					.forName("in.bench.resources.reflection.UsingClassForNameOfReflection")
					.newInstance();

			// invoking display() method
			object41.display();
		} 
		catch (InstantiationException iex) {
			iex.printStackTrace();
		} 
		catch (IllegalAccessException iaex) {
			iaex.printStackTrace();
		} 
		catch (ClassNotFoundException cnfex) {
			cnfex.printStackTrace();
		}
	}

	// display() method to test
	public void display(){
		System.out.println("Way 4.1: using Class.forName(className).newInstance()");
	}
}

Output:

newInstance() method invokes: default no-arg constructor
Way 4.1: using Class.forName(className).newInstance()

Explanation:

  • We have explicitly provided a default no-arg constructor at line no. 6
  • But if we haven’t coded any explicit constructor in the class, then compiler (or JVM) inserts a default no-arg constructor (provided there is no parameterized constructor)
  • Line no. 14 creates an Object using newInstance() method after loading respective class using Class.forName(“fully.qualified.name.of.class”)
  • When newInstance() method is executed then it invokes public default no-arg constructor
  • After object creation step, using object reference we are invoking display() method to print simple message in the console

 

Way 4.2: Reflection – <ClassName>.class.newInstance();

This is very similar to earlier approach with only difference is that, instead of loading class here it expects to know fully qualified class name

Loading –> <ClassName>.class
Creating –> invoking newInstance() method on that particular class

UsingClassNameOfReflection.java

package in.bench.resources.reflection;

public class UsingClassNameOfReflection {

	// public no-arg constructor
	public UsingClassNameOfReflection() {
		System.out.println("newInstance() method invokes: default no-arg constructor");
	}

	public static void main(String[] args) {

		try {
			// Way 4.2: using <ClassName>.class.newInstance();
			UsingClassNameOfReflection object42 = UsingClassNameOfReflection.class.newInstance();

			// invoking display() method
			object42.display();
		} 
		catch (InstantiationException iex) {
			iex.printStackTrace();
		} 
		catch (IllegalAccessException iaex) {
			iaex.printStackTrace();
		}
	}

	// display() method to test
	public void display(){
		System.out.println("Way 4.2: using <ClassName>.class.newInstance();");
	}
}

Output:

newInstance() method invokes: default no-arg constructor
Way 4.2: using <ClassName>.class.newInstance();

Explanation:

  • We have explicitly provided a default no-arg constructor at line no. 6
  • But if we haven’t coded any explicit constructor in the class, then compiler (or JVM) inserts a default no-arg constructor (provided there is no parameterized constructor)
  • Line no. 14 creates an Object using newInstance() method after getting fully qualified class name
  • When newInstance() method is executed then it invokes public default no-arg constructor
  • After object creation step, using object reference we are invoking display() method to print simple message in the console

 

Way 4.3: Reflection – using class loader

This is again very similar to earlier approaches (4.1 & 4.2), but here it uses class loader to load class

Loading –> <ClassName>.class.getClassLoader().loadClass(“qualified.class.name”)
Creating –> invoking newInstance() method on that particular loaded class

UsingClassLoaderOfReflection.java

package in.bench.resources.reflection;

public class UsingClassLoaderOfReflection {

	// public no-arg constructor
	public UsingClassLoaderOfReflection() {
		System.out.println("newInstance() method invokes: default no-arg constructor");
	}

	public static void main(String[] args) {

		// local variable
		Object object = null;

		try {
			// Way 4.3: using class loader
			object = UsingClassLoaderOfReflection.class.getClassLoader()
					.loadClass("in.bench.resources.reflection.UsingClassLoaderOfReflection")
					.newInstance();

			// type-cast to required type from Object
			UsingClassLoaderOfReflection object43 = (UsingClassLoaderOfReflection) object;

			// invoking display() method
			object43.display();
		} 
		catch (InstantiationException iex) {
			iex.printStackTrace();
		} 
		catch (IllegalAccessException iaex) {
			iaex.printStackTrace();
		} 
		catch (ClassNotFoundException cnfex) {
			cnfex.printStackTrace();
		}
	}

	// display() method to test
	public void display(){
		System.out.println("Way 4.3: using class loader;");
	}
}

Output:

newInstance() method invokes: default no-arg constructor
Way 4.3: using class loader;

Explanation:

  • We have explicitly provided a default no-arg constructor at line no. 6
  • But if we haven’t coded any explicit constructor in the class, then compiler (or JVM) inserts a default no-arg constructor (provided there is no parameterized constructor)
  • Line no. 17 creates an Object using newInstance() method, after loading respective class using class loader
  • When newInstance() method is executed then it invokes public default no-arg constructor
  • After object creation step, using object reference we are invoking display() method to print simple message in the console

 

Way 4.4: Reflection – using constructor with generics

In all earlier reflection approach, we have used only class name to load class and later creating/instantiating Object using newInstance() method. But here, we are going to use Constructor to load class in a reflective way

Loading –> <ClassName>.class.getConstructor()
Creating –> invoking newInstance() method on that particular loaded class (via Constructor)

UsingConstructorOfReflection.java

package in.bench.resources.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class UsingConstructorOfReflection {

	// public no-arg constructor
	public UsingConstructorOfReflection() {
		System.out.println("newInstance() method invokes: default no-arg constructor");
	}

	public static void main(String[] args) {

		try {
			// Way 4.4: using newInstance() method of Constructor
			Constructor<UsingConstructorOfReflection> constructor = 
					UsingConstructorOfReflection.class.getConstructor();

			// invoking newInstance() method to create Object using Reflection
			UsingConstructorOfReflection object44 = constructor.newInstance();

			// invoking display() method
			object44.display();
		} 
		catch (InstantiationException iex) {
			iex.printStackTrace();
		} 
		catch (IllegalAccessException iaex) {
			iaex.printStackTrace();
		} 
		catch (IllegalArgumentException iargex) {
			iargex.printStackTrace();
		} 
		catch (InvocationTargetException itex) {
			itex.printStackTrace();
		}
		catch (NoSuchMethodException nsmex) {
			nsmex.printStackTrace();
		} 
		catch (SecurityException sex) {
			sex.printStackTrace();
		}
	}

	// display() method to test
	public void display(){
		System.out.println("Way 4.4: using newInstance() method of Constructor");
	}
}

Output:

newInstance() method invokes: default no-arg constructor
Way 4.4: using newInstance() method of Constructor

Explanation:

  • We have explicitly provided a default no-arg constructor at line no. 9
  • But if we haven’t coded any explicit constructor in the class, then compiler (or JVM) inserts a default no-arg constructor (provided there is no parameterized constructor)
  • Line no. 17 & 21 creates an Object using newInstance() method, after loading respective class via Constructor-way
  • When newInstance() method is executed then it invokes public default no-arg constructor
  • After object creation step, using object reference we are invoking display() method to print simple message in the console

 

Exception for reflection API and newInstance() method

  • While creating Object using reflection API & newInstance() method, definitely a default no-arg constructor is required
  • It can be explicit default constructor coded in the class by programmer or else JVM provided default no-arg constructor at compile-time
  • In any case, if the corresponding class doesn’t contains default no-arg constructor then at run-time, a exception is thrown stating reason “java.lang.NoSuchMethodException” as shown in the below figure

 

Hope, you found this article very helpful. If you any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.

 

Happy Coding !!
Happy Learning !!

Singleton design pattern - restricting all 4 ways of Object creation in Java
Why the execution order of Constructor and Initialization blocks is pre-defined?