What is Cloneable Interface in Java: Explanation and Example
Cloneable interface in Java is a marker interface that indicates a class allows its objects to be cloned, meaning creating a copy of the object. When a class implements Cloneable, it enables the use of the clone() method to make a field-by-field copy of the object.How It Works
The Cloneable interface in Java is special because it does not have any methods to implement. It acts like a signal or a permission slip that tells the Java system: "It's okay to make a copy of objects from this class."
When you call the clone() method on an object, Java checks if the object's class implements Cloneable. If it does, Java creates a new object with the same values for all fields, like making a photocopy of a document. If the class does not implement Cloneable, Java throws an exception to prevent copying.
This mechanism helps avoid accidental copying of objects that should not be duplicated, ensuring safer and clearer code.
Example
This example shows a simple class Person that implements Cloneable. It overrides the clone() method to allow copying a Person object.
class Person implements Cloneable { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } @Override public String toString() { return "Person{name='" + name + "', age=" + age + "}"; } } public class Main { public static void main(String[] args) { try { Person original = new Person("Alice", 30); Person copy = (Person) original.clone(); System.out.println("Original: " + original); System.out.println("Copy: " + copy); } catch (CloneNotSupportedException e) { System.out.println("Clone not supported"); } } }
When to Use
Use the Cloneable interface when you need to create a copy of an object with the same data, especially if creating a new object manually is complex or costly. It is useful in situations like:
- Duplicating objects to modify copies without changing the original.
- Implementing prototypes where new objects are made by cloning existing ones.
- Working with collections that require copies of objects.
However, cloning can be tricky with objects that contain references to other objects (deep vs shallow copy), so use it carefully and consider alternatives like copy constructors or factory methods if needed.
Key Points
- Cloneable is a marker interface with no methods.
- Implementing it allows use of
clone()to copy objects. - Calling
clone()on a non-Cloneable object throwsCloneNotSupportedException. - Default
clone()makes a shallow copy (copies fields as is). - Override
clone()to customize copying behavior.