Cloneable Example in Java
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.
Java Program
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
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.
- 1
class Point implements Cloneable— implementing this marker interface is what makes callingclone()legal; without it,Object'sclone()throwsCloneNotSupportedExceptionat runtime. - 2
@Override public Point clone()callssuper.clone(), which performs a shallow field-for-field copy, and casts the result back toPoint. - 3
CloneNotSupportedExceptionis 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. - 4The cloned object has its own copy of
xandy, entirely separate from the original — the==check on the two references confirms they aren't the same object.
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.