aspose file tools*
The moose likes Beginning Java and the fly likes Why Clone method is Protected 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 » Java » Beginning Java
Bookmark "Why Clone method is Protected" Watch "Why Clone method is Protected" New topic
Author

Why Clone method is Protected

Ajit Kanada
Ranch Hand

Joined: Jan 23, 2001
Posts: 95
AS all the classes derive from Object class.What is the point in keeping clone() protected?
pl help...
Ajit Kanada


Thankx
Ajit
Ajit Kanada
Ranch Hand

Joined: Jan 23, 2001
Posts: 95
I m not satisfied!!!
As clone() is protected it can be accessed in the same package and also by derived classes of Object Class.But..all other classes in java are derived from Object class..
Whats the point in keeping clone() protected..
One more thing u cant use unless u implement clonacle...

John M. Gabriele
Ranch Hand

Joined: Feb 18, 2001
Posts: 232
here's something to note:
if you take a look at the source for Cloneable (note the
misspelling---it should really be Clonable) you see this:
public interface Cloneable {
}
yes, it's empty. when you declare a class and put
"implements Cloneable" after the class name, there's nothing
to implement---well, 'cept the semantics of what the interface
represents. This sort of interface is called a marker interface.
you've gotta put the "implements Cloneable" b/c when someone
calls yourRectangle.clone(), this method will internally call
Object.clone(). Object.clone() will throw an exception
(CloneNotSupportedException) if Rectangle doesn't "implement
Clonable." Also, you may be
passing your Rectangle to other methods off in other classes
that take Clonables as parameters.
so, there's no clone() method declaration in the Cloneable
interface to implement. That to me is a hint that we're s'posed
to override the inherited clone() we get from Object.
When you override a method of a superclass, we all know that
you've gotta make the new method as visible or more visible
than the method it's overriding.
At this point, I always have to remind myself whether i'm writing
a class for my own use (in my own package) or for a client's
use (over in some other package).
If someone over in another package is gonna make one of my
Rectangles and use it, they may want to clone it---so I should
make Rectangle's clone() public.
I haven't studied exceptions yet so this is as far as i've
gotten. Anyone else care to carry the torch the rest of the way?
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Why Clone method is Protected