Clone Method and Covariant Returns
What you'll learn: How Java's Object.clone() returns Object and why subclasses often override it to return their own type using covariant returns.
The Object.clone() Problem
Every class in Java inherits the clone() method from Object, but there's a quirk: Object.clone() returns type Object. This means whenever you call clone(), you get back an Object reference, even though the actual instance is a more specific type like Dog or Car.
class Dog {
String name;
// Without override, clone() returns Object
}
Dog original = new Dog();
Object copy = original.clone(); // Returns Object, not Dog!
Dog actualDog = (Dog) copy; // Requires downcasting
This forces you to downcast every time, which is inconvenient and error-prone.
Covariant Returns to the Rescue
Since Java 5, you can override clone() with a covariant return type—returning Dog instead of Object. The overriding method narrows the return type, making the API more convenient:
class Dog implements Cloneable {
String name;
@Override
public Dog clone() { // Returns Dog, not Object!
try {
return (Dog) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError(); // Can't happen
}
}
}
Dog original = new Dog();
Dog copy = original.clone(); // No cast needed!
Internally, you still call super.clone() (which returns Object) and cast it once inside your method. But callers get a Dog directly, eliminating the need for downcasting.
Why This Works
Covariance allows subclasses to return a more specific type. Since Dog is-a Object, returning Dog satisfies the contract of Object.clone() while providing better type safety for users of your class.
Key Takeaway: Object.clone() returns Object for generality, but you should override it with a covariant return type (your class's type) to eliminate downcasting and improve usability.