File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Clone Method" Watch "Clone Method" New topic

Clone Method

Akash Singhal

Joined: Feb 12, 2005
Posts: 11
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

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

Joined: Aug 31, 2004
Posts: 11343

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

"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
I agree. Here's the link:
subject: Clone Method
jQuery in Action, 3rd edition