In this article, we will discuss various ways to create an Object in Java i.e.;
Various ways to create Object in Java
Primarily, there are only 4 ways to create an object in Java, are;
- Using new operator or keyword
- Using the clone method of the Object class
- Using Object De-serialization
- Using Reflection API
But using reflection way, we can derive multiple ways to create objects in Java
Interface vs Abstract Class In Java
Let us move forward and discuss all possible ways to create an object in Java
Way 1: Using the new operator or keyword
This is a very common way to create or instantiate new objects, as shown in the below demo example
clone() method of an Object class, creates another copy of the same Object with all its details
Method signature :
protected native Object clone() throws CloneNotSupportedException;
Check Also: Positive & Negative Testing
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:
- The class for which cloning is performed must implement ”java.lang.Cloneable” interface, otherwise “java.lang.CloneNotSupportedException” will be thrown
- Explicit type-cast is required, as shown in the below figure point-1.
- It is necessary to handle compile-time exceptions either by throws clause or surrounding with a try-catch block, as shown in the below figure point-2.
Way 3: Using Object de-serialization process
This case assumes that the already object is serialized using the serialization process. Now, when the reverse process happens i.e.; de-serializing binary file format from file storage into Java’s heap memory, then a new object is created
package com.hcl.tmobile.submitservicechange; import java.io.FileInputStream; import java.io.ObjectInputStream; public class UsingDeSerialization { public static void main(String[] args) { // TODO Auto-generated method stub // 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”
- The 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 the object’s state and re-creates a new object
- In this way, a new Object can be created in Java using the 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:
Using Class.forName(“fully.qualified.name.of.class”).newInstance(); Using <ClassName>.class.newInstance(); Using <ClassName>.class.getClassLoader().loadClass(“fully.qualified.name.of.class”).newInstance(); Using Constructor i.e.; Constructor<<className>> constructor = <ClassName>.class.getConstructor(); <ClassName> object44 = constructor.newInstance();
Pre-requisite:
To create an 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()"); } }
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, the 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 the newInstance() method is executed then it invokes public default no-arg constructor
- After the object creation step, using object reference we are invoking the display() method to print a simple message in the console
Way 4.2: Reflection – <ClassName>.class.newInstance();
This is very similar to the earlier approach with the only difference is that instead of loading class here it expects to know the fully qualified class name
Loading –> <ClassName>.class
Creating –> invoking newInstance() method for that particular class
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:
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, the compiler (or JVM) inserts a default no-arg constructor (provided there is no parameterized constructor)
- Line no. 14 creates an Object using the newInstance() method after getting a fully qualified class name
- When the newInstance() method is executed then it invokes public default no-arg constructor
- After the object creation step, using object reference we are invoking the display() method to print a simple message in the console
Way 4.3: Reflection – using a class loader
This is again very similar to earlier approaches (4.1 & 4.2), but here it uses the class loader to load class
Loading –> <ClassName>.class.getClassLoader().loadClass(“qualified.class.name”)
Creating –> invoking newInstance() method on that particular loaded class
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 // 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:
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, the compiler (or JVM) inserts a default no-arg constructor (provided there is no parameterized constructor)
- Line no. 17 creates an Object using the newInstance() method, after loading a respective class using the class loader
- When the newInstance() method is executed then it invokes public default no-arg constructor
- After the object creation step, using object reference we are invoking the display() method to print a simple message in the console
Way 4.4: Reflection – using constructor with generics
In all earlier reflection approaches, we have used the only class name to load a class and later creating/instantiating Object using the 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)
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:
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, the 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 the newInstance() method is executed then it invokes public default no-arg constructor
- After the object creation step, using object reference we are invoking the display() method to print a 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 contain default no-arg constructor then at run-time, an exception is thrown stating reason “java.lang.NoSuchMethodException” as shown in the below figure
Create Object Java Program: Different Ways to Create Object In Java With Example Program
package com.softwaretestingo.java.basics; class aabc { int a,b; void m1() { System.out.println("Value Of a -- " +a); System.out.println("Value Of b -- " +b); } } public class ObjectCreation { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("======Main Starts Here====="); aabc obj=new aabc(); obj.a=20; obj.b=40; obj.m1(); System.out.println("========================="); aabc obj1=new aabc(); obj1.a=30; //obj1.b=50; obj1.m1(); System.out.println("====== Main Ends Here ========"); } }
Leave a Reply