The test case using jdk 1.8.
class C implements Cloneable
class C implements Cloneable {
int id;
public C(int id) {
this.id = id;
}
@Override
public C clone() throws CloneNotSupportedException {
return (C)super.clone();
}
}
public class CloneTest {
@Test
public void test1() throws CloneNotSupportedException {
C c1 = new C(100);
C c2 = c1.clone();
System.out.println("c1:" + c1.id);
System.out.println("c2:" + c2.id);
c2.id = 101;
System.out.println("c1:" + c1.id);
System.out.println("c2:" + c2.id);
}
}
Run the test case, it will print the following content.
c1:100
c2:100
c1:100
c2:101
Class not implements Cloneable
class C {
int id;
public C(int id) {
this.id = id;
}
@Override
public C clone() throws CloneNotSupportedException {
return (C)super.clone();
}
}
public class CloneTest {
@Test
public void test1() throws CloneNotSupportedException {
C c1 = new C(100);
C c2 = c1.clone();
System.out.println("c1:" + c1.id);
System.out.println("c2:" + c2.id);
c2.id = 101;
System.out.println("c1:" + c1.id);
System.out.println("c2:" + c2.id);
}
}
Run the test case, it will print the following content.
java.lang.CloneNotSupportedException: Item11.C
at java.lang.Object.clone(Native Method)
at Item11.C.clone(CloneTest.java:13)
at Item11.CloneTest.test1(CloneTest.java:22)
...