class CloneTest
{
public static void main(String[] args)
{
JiaoShou js=new JiaoShou("wangxing",30);
Student sd=new Student("lisi",15,js);
Student sd2=(Student)sd.clone();
sd2.js.name="lizhao";
sd2.js.age=10;
System.out.println("name="+sd.js.name+",age="+sd.js.age);
}
}class JiaoShou implements Cloneable
{
String name;
int age;
JiaoShou(String name,int age)
{
this.name=name;
this.age=age;
}
public Object clone()
{
Object ob=null;
try
{
ob=super.clone();
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
return ob;
}
}
class Student implements Cloneable
{
String name;
int age;
JiaoShou js;
Student(String name,int age,JiaoShou js)
{
this.name=name;
this.age=age;
this.js=js;
}
public Object clone()
{
Student sd=null;
try
{
sd=(Student)super.clone();
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
sd.js=(JiaoShou)js.clone();//这句表示什么?
return sd;
}
}我对Student类中的clone()方法不太懂,请各位朋友帮忙解答一下,下谢谢啦!

解决方案 »

  1.   

    因为用js对象的哦用JiaoShou类的clone()方法  返回的是Object类型的对象,把他强制转型为JiaoShou
    赋给  Student类中的js属性。
      

  2.   

    sd.js=(JiaoShou)js.clone();的解释是这样,js.clone()方法生成当前js对象的复制,在逻辑当中你自己实现了clone方法,返回值是super.clone()实际上返回对象实际类型是JiaoShou,在字面上是Object类型,然后将克隆方法的返回值强制转化为JiaoShou,也是因为返回值对象实际类型是JiaoShou(否则会报强制类型转换错误),最后是sd的js属性赋值你这段代码运行根本无法达到想要的学习效果,其实这个例子的代码写的很有问题,封装性极差,这些问题先不提,为了实现学习效果,main函数里面需要加一个输出,进行对比
    public static void main(String[] args)
        {
            JiaoShou js=new JiaoShou("wangxing",30);
            Student sd=new Student("lisi",15,js);
            Student sd2=(Student)sd.clone();
            sd2.js.name="lizhao";
            sd2.js.age=10;
            System.out.println("name="+sd.js.name+",age="+sd.js.age);
            //输出name=wangxing,age=30,因为克隆对象的改变不会对原对象产生影响
            
            System.out.println("name="+sd2.js.name+",age="+sd2.js.age);
            //输出name=lizhao,age=10,输出克隆对象
        }