public class f{
public static void main(String agr[])
{
son s=new son("hello",3);
student stu1=new student("xin",34,s);
student stu2=new student("xin2",35,s);
stu2.s.name="hello2";
stu1.s.get();
stu2.s.get();
/*为什么结果是son's name:hello2 son's age:3
son's name:hello2 son's age:3
应该结果是这样的啊:son's name:hello son's age:3
son's name:hello2 son's age:3*/
}
}
class student implements Cloneable
{ String name;
int age;
son s;
student(String name,int age,son s)
{
this.name=name;
this.age=age;
this.s=s;
}
void get()
{
System.out.println("name:"+name+" age:"+age);
}
public Object clone()
{
student p=null;
try
{
p=(student)super.clone();
}
catch(Exception e)
{
System.out.println(e.toString());
}
p.s=(son)s.clone();
return p;
}
}
class son implements Cloneable
{
String name;
int age;
son(String name,int age)
{
this.name=name;
this.age=age;
}
void get()
{
System.out.println("son's name:"+name+" son's age:"+age);
}
public Object clone()
{
Object p=null;
try
{
p=super.clone();
}
catch(Exception e)
{
System.out.println(e.toString());
}
return p;
}
}
public static void main(String agr[])
{
son s=new son("hello",3);
student stu1=new student("xin",34,s);
student stu2=new student("xin2",35,s);
stu2.s.name="hello2";
stu1.s.get();
stu2.s.get();
/*为什么结果是son's name:hello2 son's age:3
son's name:hello2 son's age:3
应该结果是这样的啊:son's name:hello son's age:3
son's name:hello2 son's age:3*/
}
}
class student implements Cloneable
{ String name;
int age;
son s;
student(String name,int age,son s)
{
this.name=name;
this.age=age;
this.s=s;
}
void get()
{
System.out.println("name:"+name+" age:"+age);
}
public Object clone()
{
student p=null;
try
{
p=(student)super.clone();
}
catch(Exception e)
{
System.out.println(e.toString());
}
p.s=(son)s.clone();
return p;
}
}
class son implements Cloneable
{
String name;
int age;
son(String name,int age)
{
this.name=name;
this.age=age;
}
void get()
{
System.out.println("son's name:"+name+" son's age:"+age);
}
public Object clone()
{
Object p=null;
try
{
p=super.clone();
}
catch(Exception e)
{
System.out.println(e.toString());
}
return p;
}
}
student stu1=new student("xin",34,s);
student stu2=new student("xin2",35,s);
改为
student stu1=new student("xin",34,s);
student stu2=(student) stu1.clone();
student stu2=new student("xin2",35,s);
这里传了new了两次 student 对象么
stu2把 stu2的值覆盖了。
对象修改了,所以就是你得到的结果。