I know this is very similar to this SO question, but all the answers in that question only talk about the CloneNotSupportedException
being thrown without the Clonable
Interface.
But I would like to know why was it implemented in that way.
If a class overrides the clone()
method and calls super.clone()
it automatically means that the Class intends to clone the object.
And since clone()
is a protected method in Object
class, no one can call clone()
on an instance if the instance's class didn't intend for clone()
to be called. So what purpose does Cloneable interface actually have?
I thought it's for superclasses to prevent a subclass from calling clone, but it turns out wrong as well.
For eg:
the below code clones the object properly and what more, the field of the super class is also copied even though the super class has not implemented
Cloneable
interface
public class Test extends Test1 implements Cloneable {
private int val;
public static void main(String[] args) {
Test test1 = new Test();
test1.val = 15;
test1.val1 = 20;
Test test2 = test1.clone();
System.out.println(test1.val);
System.out.println(test1.val1);
System.out.println(test2.val);
System.out.println(test2.val1);
}
@Override
protected Test clone() {
try {
return (Test) super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
class Test1 {
public int val1;
}
Prints: 15 20 15 20
.
Also, the Java doc of clone method says
The class Object does not itself implement the interface Cloneable, so calling the clone method on an object whose class is Object will result in throwing an exception at run time.
But since clone()
is a protected method in Object
, how will it be possible for anyone to call the clone()
method of an Object
type object??
Am I missing anything obvious here??