This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Cloning in java

 
Ritu Kapoor
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We have a clone() defined in Object class. If we try to execute a class overriding clone(), it throws CloneNotSupportedException. But if we implement Cloneable interface(which is a marker interface), everything goes fine. Now the question is, why do not we have a clone() in Cloneable interface rather then in Object class.

Is it in the Object only because we require a default implementation of a clone() and since Object is the superclass, so we cannot somehow implement that interface in Object class. But then Why do we require a Cloneable Interface at all. We can override its implementation in our subclass also.

Kindly help me to clarify my doubts.

Regards,
Ritu
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Cloneable interface should be implemented, so when asked if an object of this class is an instanceof Cloneable you get a true.

By the way, Bert Bates somewhere here on this forum wrote that clone() is not a part of the exam.



Yours,
Bu.
 
Mladen Grabowsky
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
clone() should not be used to copy objects, use copy constructors or factory methods instead.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic