Search code examples
javacloneeffective-java

Java : Questions on clone method


I am reading Effective Java and the book has the below comment on the clone method.

In practice, a class that implements Cloneable is expected to provide a properly functioning public clone method. It is not, in general, possible to do so unless all of the class’s superclasses provide a well-behaved clone implementation, whether public or protected.

Can anyone give examples of why this can't be done ?


Solution

  • Imagine one of the base classes has a private field that to be copied in a specific way for a "clone" to be semantically valid.

    If that base class does not provide a correct clone implementation, the derived class can't either - it has no way of building that private field correctly.