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;
}
...
}
Instead, if you want to change an immutable object, you must clone it and change the clone while you are creating it. A Java immutable object must have all its fields be internal, private final fields. It must not implement any setters. It needs a constructor that takes a value for every single field.
You usually create copies (clones) of an object if you want to make changes in the state of the copy without changing the state of the original object. Since the state of objects of immutable classes cannot be changed, you can use the original object without any risk of changing its state.
clone() method in Java Object class has a clone method which can be used to copy the values of an object without any side-effect. Assignment operator has a side-effect that when a reference is assigned to another reference then a new object is not created and both the reference point to the same object.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With