![]() |
VOOZH | about |
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
Now, we are going to discuss each of these methods one by one.
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.
GeeksForGeeks
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.
GeeksForGeeks
Note:
- It performs a shallow copy (deep copy needs custom implementation).
- If the class doesn't implement Cloneable, a CloneNotSupportedException will be thrown.
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.
Object has been serialized Deserialized object name: GeeksForGeeks
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.
GeeksForGeeks
This method is deprecated in Java 9 because it throws checked exceptions awkwardly and only works with no-arg public constructors
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 |