Java – implement clone () for immutable classes

I am developing a class library

>I have an abstract base class of matrix, which provides the implementation of some basic methods. > Derived from matrix, it is a specific subclass of different types of matrices. > I require that the matrix can be cloned, so the matrix implements the clonable interface. > Some classes derived from matrix are immutable

For the cloning method of immutable class, can it accept not the cloning of the object, but the object itself?

Some (oversimplified) codes are used to clarify:

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 thought I called super Clone () is enough

If your class is immutable, it should have cloned any mutable classes when it was constructed Therefore, I think it is safe for your class to have shallow copies of any field

JavaDocs declares X. clone()= X is preferred Although this is not an absolute requirement, your plan will certainly violate it

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>