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

Clone Method

 
Akash Singhal
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic