Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Cloneable

 
Mike Shn
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello
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
Bartender
Posts: 7466
50
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic