2

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 ?

Vinoth Kumar C M
  • 10,378
  • 28
  • 89
  • 130

4 Answers4

3

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
1

Basically, if part of your class hierarchy includes a class that is not under your control and not part of the JDK (ie. a 3rd party closed-source class), and this class does not implement a well-behaved clone() method, then it's not going to be particularly easy to produce one.

Crollster
  • 2,751
  • 2
  • 23
  • 34
0

In many cases a class is usually written with clone not implemented. So when a child class is written it is likewise written with clone not implmented. At some point it is required to write a clone method in a child class but it's parents don't have one.

Brett Walker
  • 3,566
  • 1
  • 18
  • 36
0
`@override
public MyClass clone(){

Myclass clonedObj = super.clone(); // This is why the classtree all needs to be cloneable

// now copy values of all members to the new obj.
// be carefull to not copy references
clonedobj.setMyMember(this.getMyMember()); // copy of member var;
clonedobj.setMyotherMember(this.getMyOtherMember().clone()); // a composit obj must be cloned.

}
`

this can be the anwser?

Zesar
  • 566
  • 2
  • 14