I am developping a class library.
- I have an abstract base class Matrix for matrices that provides implementations for some of the basic methods.
- Derived from Matrix are concrete subclasses for different types of matrices.
- I have the requirement for matrices to be cloneable, so Matrix implements the Cloneable interface.
- 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;
}
...
}
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() != xis preferred. While this isn’t an absolute requirement, it would certainly be violated by your plan to just returnthis.