• Post Reply Bookmark Topic Watch Topic
  • New Topic

clone method is protected why?  RSS feed

 
Sudhakar Sharma
Ranch Hand
Posts: 71
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
clone() method is defined in the Object class with protected modifier(why so?), although we have to implement the cloneable interface to provide an implementation of clone() method. why so? Please elaborate.

thanks & regards
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, first of all I don't think it makes much sense to clone a direct instance of java.lang.Object, so a clone() method really doesn't belong in the public API of such this non-abstract class. Furthermore, java.lang.Object is designed for inheritence; it is at the root of any type-hierarchy. Making the clone() method public would imply that any subclass of java.lang.Object would advertise that it supports cloning, even if that would make no sense or shouldn't be allowed for that particular class. The reason for it to be defined on java.lang.Object at all is to make the cloning mechanism (a native implementation) available to subclasses. Then the only reasonable option remaining, if you take the public modifier out of the equation, is to make the method protected. If a subclass want to advertise that it supports cloning on its public API it can override the clone() method, specifying the public access modifier, and invoke super.clone() to make use of java.lang.Object's implementation of clone(). It would also have to implement the Cloneable interface for this to work, otherwise the native implementation of java.lang.Object#clone() will throw CloneNotSupportedException.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And Cloneable doesn't have any methods. If you want to know why, please SearchFirst; that question has been asked several times before.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!