下面這段代碼中,為什么
//對引用的對象也進行復(fù)制
o.p=(Professor)p.clone();
就能夠?qū)崿F(xiàn)深拷貝呢?
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)
{
System.out.println(e.toString());
}
return o;
}
}
public class Student implements Cloneable
{
String name;
int age;
Professor p;
Student(String name,int age,Professor p)
{
this.name=name;
this.age=age;
this.p=p;
}
public Object clone()
{
Student o=null;
try
{
o=(Student)super.clone();
}
catch(CloneNotSupportedException e)
{
System.out.println(e.toString());
}
//對引用的對象也進行復(fù)制
o.p=(Professor)p.clone();
return o;
}
public static void main(String[] args)
{
Professor p=new Professor("wangwu",50);
Student s1=new Student("zhangsan",18,p);
Student s2=(Student)s1.clone();
s2.p.name="lisi";
s2.p.age=30;
//學生1的教授不 改變。
System.out.println("name="+s1.p.name+","+"age="+s1.p.age);
System.out.println("name="+s2.p.name+","+"age="+s2.p.age);
}
}
4 回答

胡說叔叔
TA貢獻1804條經(jīng)驗 獲得超8個贊
你這個是淺復(fù)制,只能復(fù)制基本的數(shù)據(jù)類型,要復(fù)制對象成員變量,還需要調(diào)用該成員變量的clone方法,我是這么理解的,多次淺復(fù)制實現(xiàn)深復(fù)制

郎朗坤
TA貢獻1921條經(jīng)驗 獲得超9個贊
jdk clone方法的默認實現(xiàn)都是value copy,對于基本類型,就是把copy值。對于引用,就是copy引用所指向的地址。
所以如果沒有o.p=(Professor)p.clone();
這段代碼,那么原對象和clone對象的p,引用的都是同一個Professor對象,也就是淺copy。
添加回答
舉報
0/150
提交
取消