Well, I guess you could say they're related in the sense that you can implement the clone() method using object serialization, but that's about it, I guess.
No, you don't. You can use serialisation as a cheat's method to mimic cloning, but that isn't implementing the clone() method.
Joined: Oct 30, 2001
Um, I think you can implement clone() using the serialisation method.
Normally, when one implements clone(), one calls super.clone() to do a shallow copy, then does whatever extra stuff is required. But for the serialisation method, you don't call super.clone() at all; you do all the copying yourself.
I don't recommend this approach. In fact, I don't recommend using clone() at all, if you can avoid it. But I think it is feasible.
Joined: Oct 13, 2005
I know you will call me pedantic, but you aren't using serialisation to implement clone(). You can use it to circumvent clone(). As you say, people rarely use clone() anyway.
Originally posted by Campbell Ritchie: I know you will call me pedantic, but you aren't using serialisation to implement clone(). You can use it to circumvent clone(). As you say, people rarely use clone() anyway.
I think you can do either, really. It's probably more common to use this technique to circumvent clone(), as you say. But you could also use this technique to provide a clone() implementation that gives a deep copy, without having to detail all the fields yourself. This might make sense for a base class that will be extended by many others, where you want deep copies and you don't want to have to write all those clone() methods individually. And you don't care if your clone() method is notably slower than other common implementations would be. (Like most other performance issues, most of the time it doesn't really matter anyway.) I agree that clone() isn't used that often anyway, and this usually wouldn't be a good way to implement it. But sometimes it might make sense.