It's not a secret anymore!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Clone Method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Clone Method" Watch "Clone Method" New topic
Author

Clone Method

Akash Singhal
Greenhorn

Joined: Feb 12, 2005
Posts: 11
Hi,
Why does the following code give me Error??

It gives me following error Clone() has protected access in java.lang.Object


PS :- I cleared SCJP1.4 today with 95 % (58/61)

Ren� Star
Greenhorn

Joined: Feb 24, 2005
Posts: 13
The method clone() is declared protected in the Object class. Protected methods can be accessed from within the same package or from any subclass.

Obviously you are not in the same package, but you are a subclass of Object.
HOWEVER, there is a caveat in this: a class can only access a protected members of a superclass on objects of its own class (or one of its subclasses).

Here's an example:



Which brings us to the next question: why doesn't the String class override the clone() method with a public version?
Strings are immutable, and it would not make sense to make a copy of an immutable object. Say you have a string "abcde" somewhere in memory. Why would you want to have another string "abcde" in memory? You can not change the string anyway, so you can just assign the original reference.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

There's a good explanation of cloning in Appendix A of Bruce Eckel's Thinking in Java...

http://www.faqs.org/docs/think_java/TIJ319.htm


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Clone Method