Implementing clone: Overriding and CloneNotSupportedException
What you'll learn: How to properly override the clone method, implement the Cloneable interface, and handle the checked exception that makes cloning possible.
The Protected Clone Method Problem
You've seen that Object.clone() exists and performs shallow copying, but there's a catch: it's protected, meaning you can't call it on just any object from outside its class hierarchy. To make cloning available, you must override clone and make it public.
The Three-Step Implementation Recipe
1. Implement the Cloneable interface
This marker interface (no methods!) tells the JVM your class agrees to be cloned. Without it, clone() throws CloneNotSupportedException at runtime.
2. Override clone with public access
Change visibility from protected to public so external code can call it.
3. Handle CloneNotSupportedException
Object.clone() declares this checked exception. You must catch it or declare it, even though it won't actually be thrown if you've implemented Cloneable.
The Pattern in Code
public class Book implements Cloneable {
private String title;
private int pages;
public Book(String title, int pages) {
this.title = title;
this.pages = pages;
}
@Override
public Book clone() {
try {
return (Book) super.clone(); // Call Object's clone
} catch (CloneNotSupportedException e) {
// Won't happen since we implement Cloneable
throw new AssertionError("Clone failed", e);
}
}
}
Notice the covariant return type (Book instead of Object) and the downcast from Object to Book. The exception handling is required by the compiler but becomes a formality once Cloneable is implemented.
Key Takeaway: To enable cloning, implement Cloneable, override clone() as public, call super.clone(), and handle CloneNotSupportedException (typically by wrapping in an unchecked exception since it shouldn't occur when Cloneable is present).