相關要點:
1.必須實現(xiàn)Cloneable接口,這個接口只是一個標識;如果不實現(xiàn),調(diào)用了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現(xiàn)值");
- print(a);
- System.out.println("b現(xiàn)值");
- 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);
- }
- }
結(jié)果:
a原值
a=12
b=hahaa
c=14.11
a現(xiàn)值
a=12
b=hahaa
c=14.11
b現(xiàn)值
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現(xiàn)值");
- print(a);
- System.out.println("b現(xiàn)值");
- print(b);
- }
-
- public static void print(TestShallow1 a) {
- System.out.println("a=" + a.a);
- System.out.println("b=" + a.b.a);
- }
- }
結(jié)果:
a原值
a=12
b=hahaa
a現(xiàn)值
a=12
b=hahab
b現(xiàn)值
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現(xiàn)值");
- print(a);
- System.out.println("b現(xiàn)值");
- print(b);
- }
-
- public static void print(TestDeep a) {
- System.out.println("a=" + a.a);
- System.out.println("b=" + a.b.a);
- }
- }
結(jié)果:
a原值
a=12
b=hahaa
a現(xiàn)值
a=12
b=hahaa
b現(xiàn)值
a=13
b=hahab