相关要点:
1.必须实现Cloneable接口,这个接口只是一个标识;如果不实现,调用了clone(),运行时会报CloneNotSupportedException
2.clone是Object的方法,标识为protected,子类必须重写,标识符可改为public
3.对于jdk1.5,clone可以返回相应类的类型或Object;对于1.4,只能返回Object
4.注意深复制和浅复制
浅复制
(1)对于int,double,Double,String等基本类型,super.clone()是采用的深复制
- public class TestShallow implements Cloneable {
- public int a;
- public String b;
- public Double c;
- public TestShallow clone() throws CloneNotSupportedException{
- return (TestShallow)super.clone();
- }
- }
- class Test {
- public static void main(String[] args) throws CloneNotSupportedException {
- TestShallow a = new TestShallow();
- a.a = 12;
- a.b = "hahaa";
- a.c = 14.11;
- System.out.println("a原值");
- print(a);
- TestShallow b = a.clone();
- b.a = 13;
- b.b = "hahab";
- b.c = 15.11;
- System.out.println("a现值");
- print(a);
- System.out.println("b现值");
- print(b);
- }
-
- public static void print(TestShallow a) {
- System.out.println("a=" + a.a);
- System.out.println("b=" + a.b);
- System.out.println("c=" + a.c);
- }
- }
结果:
a原值
a=12
b=hahaa
c=14.11
a现值
a=12
b=hahaa
c=14.11
b现值
a=13
b=hahab
c=15.11
(2)对其他类及自定义类,默认采用的是浅复制
- class A {
- public String a;
- }
- public class TestShallow1 implements Cloneable {
- public int a;
- public A b;
- public TestShallow1() {
- b = new A();
- }
- public TestShallow1 clone() throws CloneNotSupportedException{
- return (TestShallow1)super.clone();
- }
- }
- class Test1 {
- public static void main(String[] args) throws CloneNotSupportedException {
- TestShallow1 a = new TestShallow1();
- a.a = 12;
- a.b.a = "hahaa";
- System.out.println("a原值");
- print(a);
- TestShallow1 b = a.clone();
- b.a = 13;
- b.b.a = "hahab";
- System.out.println("a现值");
- print(a);
- System.out.println("b现值");
- print(b);
- }
-
- public static void print(TestShallow1 a) {
- System.out.println("a=" + a.a);
- System.out.println("b=" + a.b.a);
- }
- }
结果:
a原值
a=12
b=hahaa
a现值
a=12
b=hahab
b现值
a=13
b=hahab
深复制
对于其中非基本类型的字段,必须明确进行其赋值
- class A implements Cloneable {
- public String a;
- public A clone() throws CloneNotSupportedException{
- return (A)super.clone();
- }
- }
- public class TestDeep implements Cloneable {
- public int a;
- public A b;
- public TestDeep() {
- b = new A();
- }
- public TestDeep clone() throws CloneNotSupportedException{
- TestDeep clone = (TestDeep)super.clone();
- clone.b = this.b.clone();
- return clone;
- }
- }
- class Test1 {
- public static void main(String[] args) throws CloneNotSupportedException {
- TestDeep a = new TestDeep();
- a.a = 12;
- a.b.a = "hahaa";
- System.out.println("a原值");
- print(a);
- TestDeep b = a.clone();
- b.a = 13;
- b.b.a = "hahab";
- System.out.println("a现值");
- print(a);
- System.out.println("b现值");
- print(b);
- }
-
- public static void print(TestDeep a) {
- System.out.println("a=" + a.a);
- System.out.println("b=" + a.b.a);
- }
- }
结果:
a原值
a=12
b=hahaa
a现值
a=12
b=hahaa
b现值
a=13
b=hahab