Question

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 ?

Was it helpful?

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.

OTHER TIPS

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.

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.

`@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?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top