• Post Reply Bookmark Topic Watch Topic
  • New Topic

What is the point of making a method (clone) "protected" in Object?  RSS feed

 
Arun Singh Raaj
Ranch Hand
Posts: 31
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Q1) When all classes are child of Object class, why is clone() protected?
Q2) When should i override clone() method?
Q3) Why is it must to implement Cloneable interface when you clone()?
Q4) Why can't a String object call clone() method?

Thanks in advance
 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arun Singh Raaj wrote:Q1) When all classes are child of Object class, why is clone() protected?

Because you don't want the clone() method of one class to be able to be invoked by another class, unless the class is cloneable.

Q2) When should i override clone() method?

If you want the class to be cloneable.

Q3) Why is it must to implement Cloneable interface when you clone()?

Because the Java language assigns special meaning to the Cloneable interface, and you can not clone classes unless they implement it.

Q4) Why can't a String object call clone() method?

You mean, why can't you call clone() on a String object? Because there is no point to cloning immutable objects. Normally you would clone an object so you still have an original copy before you make changes to the object. Since you can't make changes to strings, there is no need to clone them. If you *really* want to create a new instance of a String with the same value, you can use the new String(String original) constructor. Note the last line of the description of the constructor though:

Java Platform, Standard Edition 8 API Specification wrote:Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!