What does this sentence mean? Let's look at an example.
class Dog implements Cloneable{
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public Dog clone() {
try {
return (Dog) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
}
public class MyClone {
public static void main(String[] args){
Dog dog = new Dog("dog",1);
System.out.println(dog.clone());
}
}
It runs fine. Now take out the cloneable interface
The result is
java.lang.CloneNotSupportedException: clone.Dog
at java.lang.Object.clone(Native Method)
at clone.Dog.clone(MyClone.java:22)
at clone.MyClone.main(MyClone.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
null
This says clone() method does not work without the Cloneable interface.