Course contentsShow
← Java
Lesson 561 of 2,87013. The Object Class and Common MethodsFree lesson

The Cloneable Interface and Object.clone

Understand the Cloneable marker interface and how Object.clone creates copies of objects.

The Cloneable Interface and Object.clone

What you'll learn: How Java's Cloneable marker interface and Object.clone method work together to create copies of objects.

What Is Cloneable?

Cloneable is a marker interface — it has no methods at all. Its sole purpose is to signal that a class permits cloning. If you try to call clone() on an object whose class doesn't implement Cloneable, Java throws a CloneNotSupportedException.

How Object.clone Works

Every class inherits the clone() method from Object. By default, it's protected, meaning you typically override it as public to make it accessible. When you call clone():

  1. Java checks if the class implements Cloneable
  2. If yes, it creates a shallow copy — a new object with the same field values
  3. If no, it throws an exception

Shallow copy means primitive fields are duplicated, but reference fields point to the same objects as the original.

Basic Pattern

public class Book implements Cloneable {
    private String title;
    private int pages;

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

Notice how you must:

  • Implement Cloneable (the marker)
  • Override clone(), typically changing visibility to public
  • Call super.clone() to do the actual copying

Why This Design?

The Cloneable interface acts as a permission flag. Without it, Object.clone refuses to work. This prevents accidental copying of objects that weren't designed for cloning (like objects with file handles or network connections).

Key Takeaway: Cloneable is a marker interface that grants permission for Object.clone to create shallow copies of your object; without it, cloning throws an exception.