This week's book giveaway is in the Android forum.
We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes  By using Cloneable Method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark " By using Cloneable Method" Watch " By using Cloneable Method" New topic

By using Cloneable Method

Viswanath Chakravarthy

Joined: Feb 06, 2007
Posts: 1
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

Joined: Jan 05, 2007
Posts: 108
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.

thanks,<br />gaurav abbi
Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
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

Joined: Oct 30, 2001
Posts: 1970
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.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
It is sorta covered in the JavaRanch Style Guide.
subject: By using Cloneable Method
It's not a secret anymore!