clone method call non-private, non-final methods

P

puzzlecracker

I saw it in the Effective Java book, though understanding still eludes
me (I suspect it goes on par with the constructor's contract). I don't
see implications whereby clone calls some public method to copy parts
of the object, resulting in the disaster or the end of the world sort
of a thing. Can someone illustrate that?


Thanks
 
P

puzzlecracker

     Are you sure you've read the prohibition correctly?  I can
think of no reason to avoid calling public methods in a clone()
implementation, although there are excellent reasons to avoid
calling overridable methods, the same reasons to avoid calling
them from constructors.  Are you sure you haven't read "public"
where EJ actually says "non-final?"

Yes, he refers to public (In clone chapter, 2nd edition), because, as
you said, they can be overridable.

What is the issue with that?
 
D

Daniel Pitts

puzzlecracker said:
I saw it in the Effective Java book, though understanding still eludes
me (I suspect it goes on par with the constructor's contract). I don't
see implications whereby clone calls some public method to copy parts
of the object, resulting in the disaster or the end of the world sort
of a thing. Can someone illustrate that?


Thanks

class MyClonable implements Clonable {
int cloneCount;

public void setCloneCount(int cloneCount) {
this.cloneCount = cloneCount;
}

protected MyClonable clone() {
MyClonable myClone = (MyClonable)super.clone();
myClone.setCloneCount(value + 1);
}
}

class MyClonableBreakers extends MyClonable {
public void setCloneCount(int cloneCount) {
this.cloneCount = 0;
}
}


The contract of clone() that is given by MyClonable is broken by the
derived class, without touching the clone method.

This is obviously a contrived example, but it shows what could happen
(maliciously or accidentally).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top