Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
    ...
}
like image 722
Axel Avatar asked Nov 03 '12 09:11

Axel


People also ask

How can we clone a immutable class?

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.

Do immutable classes need to be copied?

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.

What is clone () method?

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.


1 Answers

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.

like image 64
Duncan Jones Avatar answered Oct 08 '22 07:10

Duncan Jones