Java ProgramsOOPCloneable Example

Cloneable Example in Java

intermediate·  OOP  ·  Object Class

Problem

A class that implements the Cloneable marker interface and overrides clone() can produce a field-for-field copy of an object through Object's own cloning machinery, instead of copying fields by hand.

Create a Point class that supports cloning, and confirm the clone is a separate object from the original.

Input
point.clone()
Output
Original: (3, 4), Clone: (3, 4), Same object: false

Java Program

Java
public class Point implements Cloneable { private int x; private int y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public Point clone() { try { return (Point) super.clone(); // Object's clone() copies every field } catch (CloneNotSupportedException e) { throw new AssertionError(e); // never happens — Point implements Cloneable } } public static void main(String[] args) { Point original = new Point(3, 4); Point copy = original.clone(); System.out.println("Original: (" + original.x + ", " + original.y + "), " + "Clone: (" + copy.x + ", " + copy.y + "), Same object: " + (original == copy)); } }

Output

Original: (3, 4), Clone: (3, 4), Same object: false

Core Logic

Implementing Cloneable and calling super.clone() delegates the actual field-copying work to Object's built-in implementation, instead of writing a copy constructor by hand.

How It Works
  1. 1class Point implements Cloneable — implementing this marker interface is what makes calling clone() legal; without it, Object's clone() throws CloneNotSupportedException at runtime.
  2. 2@Override public Point clone() calls super.clone(), which performs a shallow field-for-field copy, and casts the result back to Point.
  3. 3CloneNotSupportedException is declared as checked, so the override either has to declare it too or catch it internally — this example catches it, since implementing Cloneable already guarantees it won't actually be thrown.
  4. 4The cloned object has its own copy of x and y, entirely separate from the original — the == check on the two references confirms they aren't the same object.
Cloning a Point(3, 4) produces a second object with the same coordinates, but original == clone is false, since they're two distinct objects in memory.
💡

Key Point: A copy constructor achieves the same end result by hand-copying fields in a constructor instead — Cloneable's clone() lets Object's own machinery do that copying instead, at the cost of Cloneable's somewhat awkward checked-exception and marker-interface requirements.

Key Concepts

Cloneableclone()CloneNotSupportedException

Related Programs