Self Test Java -2
In the same pattern as of last post, I have a new question. Just the difference this time is the question was asked by my brother.
- Ques:Why is clone method declared protected in Java (object class)
I thought hard and thought process led me to the basic difference between public and protected method. For One. And for second thing, I thought deeply about the Clonable interface may be for the first time. Obviously if a method is defined protected, it is supposed to be used in the class hierarchy only. It can not be called from outside.
1.But why it is kept protected?
2.And doesn’t Object class provide any implementation of clone(). Does it return null? Does nothing? Throw an exception?
3. What’s the use of Clonebale interface?
Answers in that order:
1. It’s kept protected because of the reason so that in your class hierarchy you can provide “deep copy” or “shallow copy” and you have to take a stand.
Let’s say with example ( Reason)
2. for second take straight from Sun javadoc:
“The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned.”
3.Brings us back to the debate of marker interface. Leave that. Its more debatable than that because of the way clone() has been defined in Object class. Because of its access modifier. This is what I have to say (echo-ing somebody else views):
“You can’t clone anything that doesn’t implement the Cloneable interface, but just because something implements the Cloneable interface doesn’t mean you can clone it”
Comments (in fact calrity) invited.