Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

By using Cloneable Method

 
Viswanath Chakravarthy
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you explain what is Clone() Method with example? If i clone a class having protected method why it is giving can't access protected method clone ? and why? Please explain.
 
gaurav abbi
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Viswanath,
the clone method is use to make a copy of a Object on which it is invoked like this

CloneTest clone1 = new CloneTest(2);
CloneTest clone2 = (CloneTest)clone1

clone2 is a copy of clone1 as far contents are concerned., but this copy can be shallow or deep, for more details refer javadoc.

regarding the error you are getting, this will come if you try to call clone method on a paricular type from some other class other than of same type because thats what protected is meant for.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by gaurav abbi:
CloneTest clone1 = new CloneTest(2);
CloneTest clone2 = (CloneTest)clone1

clone2 is a copy of clone1 as far contents are concerned.,


In that code clone1 and clone2 both reference the same object. The second line should be and the CloneTest class will have to have overridden the clone() method.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think clone() is one of the most broken parts of Java. It's just a mess. I'm pretty sure Sun wouldn't design it like it is, if they were able to start again now, but of course they can't change it now.

Personally, I prefer to avoid clone() as much as possible. One can often achieve the same sort of thing with just a little plain Java code, which will be much clearer.

YMMV.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic