File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Cloneable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Cloneable" Watch "Cloneable" New topic


Mike Shn
Ranch Hand

Joined: May 26, 2001
Posts: 149
if in class I write
class Car extends Vehicle implements Cloneable {
does it means that I can easily write:
Car c1 = new Car("New York A12 345", 150.0);
Car c2 = c1.clone();
or I need to implement the c1.clone()?
Thanks a lot

Junilu Lacar

Joined: Feb 26, 2001
Posts: 6529

Cloneable is a marker interface and does not have any methods that need to be implemented. The default clone() method is inherited from Object so you would just override it.
As for overriding clone(), it depends on how you want clone() to behave and what kind of member variables your class has. The default clone() inherited from Object performs a "shallow copy": it just copies member variables as if by assignment.
A shallow copy may not be sufficient if the object you are cloning contains references to other mutable objects. With a shallow copy, the clone will really just "share" the same object referenced by the original instead of having its own copy. If the referenced object is immutable it's not a problem. But if the object is not immutable, changes made by the clone to the referenced object will be visible from the original and vice versa.
So, if the Cloneable object contains references to mutable objects, you should override clone() to perform a "deep copy". With a deep copy, you would clone referenced objects as well.
Caveat: be careful when performing a deep copy. If you have many levels of containment/aggregation, your clone() operation may become a costly recursive exercise. Same is true for the Serializable interface.

Junilu Lacar
Sun Certified Programmer for the Java� 2 Platform

Junilu - [How to Ask Questions] [How to Answer Questions]
I agree. Here's the link:
subject: Cloneable
It's not a secret anymore!