clone() 是protected的作用域。继承Cloneable接口后要重写方法,然后在方法里调用父类的clone()的方法。同时默认的克隆对于引用对象只是浅克隆。给你一段代码自己去运行试试吧:
package cesar.Test0810;
/**
* Created by Cesar on 2016/8/10.
*/
public class A implements Cloneable{
private int a;
private B b;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public B getB() {
return b;
}
@Override
public String toString() {
return "A{" +
"a=" + a +
", b=" + b +
'}';
}
public void setB(B b) {
this.b = b;
}
protected A clone() throws CloneNotSupportedException {
return (A) super.clone();
}
}
package cesar.Test0810;
/**
* Created by Cesar on 2016/8/10.
*/
public class B {
private int b1;
private int b2;
@Override
public String toString() {
return "B{" +
"b1=" + b1 +
", b2=" + b2 +
'}';
}
public B(int b1, int b2){
this.b1 = b1;
this.b2 = b2;
}
public int getB1() {
return b1;
}
public void setB1(int b1) {
this.b1 = b1;
}
public int getB2() {
return b2;
}
public void setB2(int b2) {
this.b2 = b2;
}
}
package cesar.Test0810;
/**
* Created by Cesar on 2016/8/10.
*/
public class TestClone {
public static void main(String[] args) {
A a = new A();
B b = new B(1, 2);
a.setA(10);
a.setB(b);
try {
A a1 = a.clone();
System.out.println("a=" + a.toString());
System.out.println("a1=" + a1.toString());
a.setA(1000);
a.getB().setB1(10000);
a.getB().setB2(8000);
System.out.println("a=" + a.toString());
System.out.println("a1=" + a1.toString());
a.setB(new B(9999,9999));
System.out.println("a=" + a.toString());
System.out.println("a1=" + a1.toString());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
其中A继承了cloneable接口,同时持有了对B的引用。