VOOZH about

URL: https://www.geeksforgeeks.org/java/cloneable-interface-in-java/

⇱ Cloneable Interface in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Cloneable Interface in Java

Last Updated : 8 Oct, 2025

In Java, the Cloneable interface is a marker interface used to indicate that a class allows creating an exact copy of its objects. It is part of java.lang package and is primarily used with the Object.clone() method to create duplicates of objects.

  • It does not contain any methods (Marker Interface).
  • Its main purpose is to signal to the Object.clone() method that the objects of this class can be safely cloned.
  • If a class implements Cloneable, calling clone() on its objects will create a shallow copy.

Syntax

class ClassName implements Cloneable {

// class fields and methods

}

Example 1: Basic Shallow Cloning

This example shows how to create a shallow copy using the Cloneable interface and clone() method, we achieve shallow cloning by simply calling super.clone().


Output
Original: Alice, 25
Clone: Alice, 25
After modification:
Original: Alice
Clone: Bob

Explanation:

  • The clone() method creates a copy of the object.
  • Modifying the clone does not affect the original object because each object has its own memory.
  • Cloneable is a marker interface that signals Object.clone() can safely copy the object.

Example 2: Deep Copy Example

This example demonstrates a deep copy in Java, where the object and its nested objects are fully duplicated, so changes to the clone do not affect the original.


Output
Original City: New York
Clone City: London

Advantages of Using Cloneable

  • Easy Object Copying: Simplifies creation of object copies.
  • Improves Performance: Faster than manually creating a new object and copying all fields.
  • Customizable Cloning: Can implement shallow or deep cloning as needed.
  • Useful in Prototyping: Quickly generate copies of objects without reinitializing them.

Related Article

Shallow vs deep copy


Comment
Article Tags: