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

Clone and Inheritance: Calling super.clone

Understand why calling super.clone is critical and how it ensures correct object type.

Clone and Inheritance: Calling super.clone

You'll learn why calling super.clone() is essential for maintaining the correct object type through inheritance hierarchies.

The Problem Without super.clone

When you override clone() in a class hierarchy, you might be tempted to use new to create a fresh instance. However, this breaks down when subclasses extend your class. The subclass's clone() would return the parent type instead of the actual subclass type—a disaster for polymorphism.

Why super.clone Is Critical

The clone() method in Object has special knowledge: it creates an instance of the actual runtime class, not just the declared type. When you call super.clone() all the way up to Object.clone(), the JVM creates the correct object type automatically.

Think of it like a factory assembly line: each level in the inheritance chain adds its own customizations, but they all rely on the same original blueprint (the actual object type) created at the top.

The Call Chain

class Parent implements Cloneable {
    @Override
    public Parent clone() throws CloneNotSupportedException {
        return (Parent) super.clone(); // Calls Object.clone
    }
}

class Child extends Parent {
    @Override
    public Child clone() throws CloneNotSupportedException {
        return (Child) super.clone(); // Calls Parent.clone, which calls Object.clone
    }
}

Notice each level calls super.clone(). This chain ensures Object.clone() is ultimately invoked, which creates an instance of Child when cloning a Child object, not a Parent.

Key Takeaway: Always call super.clone() in your clone implementations to ensure the JVM creates the correct runtime type; creating objects with new breaks subclass cloning by returning the wrong type.