I am developping a class library.
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() != x
is preferred. While this isn't an absolute requirement, it would certainly be violated by your plan to just return this
.