这是我写的三个类,在test类中访问clone方法为什么不行,我知道clone方法在Object类中定义的是protected,但我还是不明白,请高手给我讲一下,不胜感激!
package chapter8a_2;public class Student implements Cloneable{
private String name;
private int age;
private Teacher t; public Student(String name, int age, Teacher t) {
super();
this.name = name;
this.age = age;
this.t = t;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Teacher getT() {
return t;
}
public void setT(Teacher t) {
this.t = t;
}



}
package chapter8a_2;public class Teacher implements Cloneable{
private int age;


public Teacher(int age) {
super();
this.age = age;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
}

}
package chapter8a_2;public class Test {
public static void main(String[] args) {
Student s=new Student("zhangsan",16,new Teacher(26));
Student s1=null;
s1=(Student)s.clone();在这里出错 }}

解决方案 »

  1.   

    你也晓得是protected方法,所以除了在java本身的包中访问外就只有子类可以访问了。因为所有的类都继承了Object,所以所有的类都有一个protected clone()方法,但是只能在其类本身访问其自身的clone()方法,如果你在其它的类中就像你的代码中在Test类中访问Student的clone()受保护的clone()方法,显然就会编译出错了。所以要想在其它的类中访问就只能重写clone()方法并扩展其访问权限变成public就可以在其它类中访问了。所以你可以在Student中重写clone()方法,如:public Object clone() {
        Object o = null
        o = super.clone();
        return o;
    }
      

  2.   

    覆盖父类的 clone 方法。然后在里面明确调用 super.clone();仅此而已,有时候不是技术上的问题,而是约定,不管是基于安全假设还是别的。
      

  3.   

    对不起:
    这里还个异常:  public Object clone() {
        Object o = null;
        try {
          o = super.clone();
        } catch(CloneNotSupportedException e) {
          System.err.println("MyObject can't clone");
        }
        return o;
      }