java 对象克隆_JAVA对象克隆
1> 為了獲取對象的一份拷貝,我們可以利用Object類的clone()方法。
2> 在派生類中覆蓋基類的clone(),并聲明為public。
3> 在派生類的clone()方法中,調(diào)用super.clone()。
4> 在派生類中實(shí)現(xiàn)Cloneable接口。
4> 沒有抽象方法的接口叫標(biāo)識接口。
5> 為什么我們在派生類中覆蓋Object的clone()方法時,一定要調(diào)用super.clone()呢?在運(yùn)行時刻,Object 的clone()方法能識別出你要復(fù)制的是哪一個對象,然后為此對象分配空間,并進(jìn)行對象的復(fù)制,將原 始對象的內(nèi)容一一復(fù)制到新的對象空間去。
* 淺克隆是針對沒有引用類型的變量來克隆。針對引用類型的克隆應(yīng)該用Deeply Clone。
淺克隆:
Code:
class FleetClone
{
public static void main(String[] args)
{
Professor p=new Professor("feiyang",23);
Student s1=new Student("zhangshan",18,p);
Student s2=(Student)s1.clone();
s2.p.name="feifei";
s2.p.age=30;
System.out.println("name="+s1.p.name+","+"age="+s1.p.age);
}
}
class Professor
{
String name;
int age;
Professor(String name,int age)
{
this.name=name;
this.age=age;
}
}
class Student implements Cloneable
{
Professor p;
String name;
int age;
Student(String name, int age,Professor p)
{
this.name=name;
this.age=age;
this.p=p;
}
public Object clone()
{
Object o=null;
try
{
o=super.clone();
}
catch(CloneNotSupportedException e)
{
e.printStackTrace();
}
return o;
}
}
改變學(xué)生s2的教授信息,打印s1教授信息,結(jié)果為:name=feifei,age=30.產(chǎn)生這個結(jié)果是因?yàn)镾tring是一個常量類型.
深克隆
code:
class DeeplyClone
{
public static void main(String[] args)
{
Professor p=new Professor("feiyang",23);
Student s1=new Student("zhangshan",18,p);
Student s2=(Student)s1.clone();
s2.p.name="Bill.Gates";
s2.p.age=30;
System.out.println("name="+s1.p.name+","+"age="+s1.p.age);
}
}
class Professor implements Cloneable
{
String name;
int age;
Professor(String name,int age)
{
this.name=name;
this.age=age;
}
public Object clone()
{
Object o=null;
try
{
o=super.clone();
}
catch(CloneNotSupportedException e)
{
e.printStackTrace();
}
return o;
}
}
class Student implements Cloneable
{
Professor p;
String name;
int age;
Student(String name, int age,Professor p)
{
this.name=name;
this.age=age;
this.p=p;
}
public Object clone()
{
//Object o=null;
Student o=null;
try
{
o=(Student)super.clone();
}
catch(CloneNotSupportedException e)
{
e.printStackTrace();
}
o.p=(Professor)p.clone();
return o;
}
}
打印結(jié)果為:name=Bill.Gates,age=30,這就是深克隆.
總結(jié)
以上是生活随笔為你收集整理的java 对象克隆_JAVA对象克隆的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 信用卡转账要多久到账 不同银行时间不一样
- 下一篇: 纯白户哪家信用卡好办 不信你就吃亏了