Search code examples
javacloneclass-designimmutability

Implementing clone() for immutable classes


I am developping a class library.

  1. I have an abstract base class Matrix for matrices that provides implementations for some of the basic methods.
  2. Derived from Matrix are concrete subclasses for different types of matrices.
  3. I have the requirement for matrices to be cloneable, so Matrix implements the Cloneable interface.
  4. Some of the classes derived from Matrix are immutable

Would it be acceptable for the immutable classes' clone methods that instead of returning a clone of the object, the object itself is returned?

Some (oversimplified) code for clarification:

abstract class Matrix implements Cloneable {
   ...
}

class ImmutableMatrix extends Matrix {
    ImmutableMatrix clone() {
        return this;
    }
    ...
}

class SomeOtherMatrix extends Matrix {
    SomeOtherMatrix clone() {
        SomeOtherMatrix other = super.clone();
        ...
        return other;
    }
    ...
}

Solution

  • I would have thought calling super.clone() would be sufficient.

    If your class is immutable then it should have already cloned any mutable classes when it was constructed. Hence I would think it would be safe to have shallow copies of any fields your class has.

    The JavaDocs state that x.clone() != x is preferred. While this isn't an absolute requirement, it would certainly be violated by your plan to just return this.