Different Ways to Create Objects in Java
Java is an object-oriented programming language where objects are instances of classes. Creating objects is one of the most fundamental concepts in Java. In Java, a class provides a blueprint for creating objects. Most of the time, we use the new keyword to create objects but Java also offers several other powerful ways to do so.
In this article, we will discuss five different methods to create objects in Java, and going to discuss how each one works internally
List of Methods to Create Objects in Java
- Using new keyword
- Using clone() method
- Using Deserialization
- Using Constructor.newInstance() from Reflection API
- Using Class.forName().newInstance()
Now, we are going to discuss each of these methods one by one.
Method 1: Using new Keyword (Most Common)
Using the new keyword is the most basic and easiest way to create an object in Java. Almost 99% of objects are created in this way. new keyword allows us to call any constructor, whether it's a default or parameterized one.
Example: This example demonstrates how to create an object in Java using the new keyword and access its instance variable.
// Java program to Illustrate Creation of Object
// Using new keyword
// Main class
class GFG {
// Declaring and initializing string
// Custom input string
String name = "GeeksForGeeks";
// Main driver method
public static void main(String[] args)
{
// As usual and most generic used we will
// be creating object of class inside main()
// using new keyword
GFG obj = new GFG();
// Print and display the object
System.out.println(obj.name);
}
}
Output
GeeksForGeeks
Method 2: Using clone() Method
The clone() method creates a shallow copy of the object. It does not invoke any constructor. The class must implement the Cloneable interface and override the clone() method.
Example: This example demonstrates how to create a copy of an object in Java using the clone() method.
// Java program to demonstrate object creation using the
// clone() method
class GFG implements Cloneable {
// Instance variable
String name = "GeeksForGeeks";
// Overriding the clone() method from Object class
@Override
protected Object clone()
throws CloneNotSupportedException
{
return super
// Calls Object class's clone() method
.clone();
}
// Main method
public static void main(String[] args)
{
try {
// Creating the first object
GFG obj1 = new GFG();
// Creating a clone (copy) of obj1
GFG obj2 = (GFG)obj1.clone();
// Printing the value of name from the cloned
// object
System.out.println(obj2.name);
}
catch (CloneNotSupportedException e) {
// Handling exception if cloning is not
// supported
e.printStackTrace();
}
}
}
Output
GeeksForGeeks
Note:
- It performs a shallow copy (deep copy needs custom implementation).
- If the class doesn't implement Cloneable, a CloneNotSupportedException will be thrown.
Method 3: Using Deserialization
When an object is deserialized, Java creates a new object without calling the constructor. The class must implement the Serializable interface.
Example: This example demonstrates how to serialize and deserialize a Java object using ObjectOutputStream and ObjectInputStream.
import java.io.*;
// Class GFG implements Serializable to allow object serialization
class GFG implements Serializable {
String name;
GFG(String name) {
this.name = name;
}
// Method to serialize the object
public static void serialize() {
try {
GFG obj = new GFG("GeeksForGeeks");
FileOutputStream fos = new FileOutputStream("file.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.close();
fos.close();
System.out.println("Object has been serialized");
} catch (IOException e) {
e.printStackTrace();
}
}
// Method to deserialize the object
public static void deserialize() {
try {
FileInputStream fis = new FileInputStream("file.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
GFG obj = (GFG) ois.readObject();
ois.close();
fis.close();
System.out.println("Deserialized object name: " + obj.name);
} catch (Exception e) {
e.printStackTrace();
}
}
// Main method
public static void main(String[] args) {
// First serialize the object
serialize();
// Then deserialize it and print the name
deserialize();
}
}
Output
Object has been serialized Deserialized object name: GeeksForGeeks
Method 4: Using Constructor.newInstance() from Reflection API
Constructor.newInstance() method is part of Java's Reflection API and can be used to invoke private constructors, parameterized constructors, or even bypass normal object instantiation flow.
Example: This example demonstrates how to create an object in Java using reflection with Constructor.newInstance(), even if the constructor is private.
// Importing the Constructor class from java.lang.reflect package
import java.lang.reflect.Constructor;
// Defining the class
class GFG {
// Private member variable
private String name;
// Public no-argument constructor
public GFG() {}
// Setter method to assign a value to 'name'
public void setName(String name) {
this.name = name;
}
// Main method – entry point of the program
public static void main(String[] args) {
try {
// Getting the Constructor object for GFG class (no-arg constructor)
Constructor<GFG> constructor = GFG.class.getDeclaredConstructor();
// Making the constructor accessible (useful if it's private)
constructor.setAccessible(true);
// Creating a new instance of GFG using the constructor
GFG obj = constructor.newInstance();
// Setting the name using the setter method
obj.setName("GeeksForGeeks");
// Printing the name to verify object creation
System.out.println(obj.name);
} catch (Exception e) {
// Handling exceptions that may occur during reflection
e.printStackTrace();
}
}
}
Output
GeeksForGeeks
Method 5: Class.forName().newInstance()
This method is deprecated in Java 9 because it throws checked exceptions awkwardly and only works with no-arg public constructors
// Deprecated example
try {
GFG obj = (GFG) Class.forName("GFG").newInstance();
} catch (Exception e) {
e.printStackTrace();
}
Comparison of Java Object Creation Methods
The table below demonstrates the comparison between these methods:
Method | Call Constructor | Use Case | Performance |
---|---|---|---|
new | Yes | General-purpose object creation | Fastest |
Constructor.newInstance() | Yes | Dynamic object creation (Reflection) | Slower |
clone() | No | Shallow/deep copying | Medium |
Deserialization | No | Restoring serialized objects | Slowest |