VOOZH about

URL: https://www.geeksforgeeks.org/java/clone-method-in-java-2/

⇱ clone() Method - Object Cloning in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

clone() Method - Object Cloning in Java

Last Updated : 10 Jun, 2026

Object cloning in Java is the process of creating an exact copy of an existing object. The clone() method, defined in the Object class, is used to perform cloning and create a new object with the same state as the original object.

  • Reduces manual effort compared to copy constructors.
  • Throws CloneNotSupportedException if cloning is not supported.
  • Helps duplicate object state efficiently.

Syntax

class MyClass implements Cloneable {
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}

Example: Program to demonstrate object cloning using the clone() method


Output
o1: 10 20
o2: 10 20

Explanation: The object o1 is cloned using the clone() method, creating a new object o2 with the same field values. Although both objects contain identical data, they occupy different memory locations.

Example: Program to demonstrate object cloning (shallow copy)


Output
Original: GFG{name:'Ram', age:24}
Cloned: GFG{name:'Ram', age:24}

Explanation: In the above example, the clone() method is overridden in the GFG class to perform a shallow copy of the object. This creates a new object "p2" with the same values as the original object "p1", but changes to immutable fields like String do not affect each other.

Example: Program to demonstrate deep copy using clone()


Output
10 20 30 40
100 20 300 40

Explanation: In the above example, we can see that a new object for the Test class has been assigned to copy an object that will be returned to the clone method. Due to this, t3 will obtain a deep copy of the object t1. So any changes made in the ā€˜c’ object fields by t3, will not be reflected in t1.

Shallow Copy Vs Deep Copy

FeatureShallow CopyDeep Copy
Object CreationNew object createdNew object created
Referenced ObjectsShared between copiesIndependently copied
Memory UsageLessMore
PerformanceFasterSlower
Data IndependenceLowerHigher

Advantages of the clone() Method

  • Creates object copies quickly and efficiently.
  • Reduces the need for manually copying fields.
  • Preserves the state of the original object.
  • Useful when duplicate objects are required.
  • Simplifies object duplication in large classes.

Note: We can use the Assignment Operator to create a copy of the reference variable. This creates a shallow copy, means both variables will refer to the same object in memory. This is not the same as cloning, where a new object is created.

Comment
Article Tags:
Article Tags: