class Copy
{
 public static void main(String[] args)
 {
    CopySub sub=new CopySub("abc",18);
    CopySub test=(CopySub)sub.clone();
    test.name="def";
    test.age=16;
    System.out.println("test's name is"+test.name+"and"+"age is "+test.age);
 }
}class CopySub implements Cloneable
{

  String name;
  int age;
  CopySub(String name,int age)
  {
     this.name=name;
     this.age=age;
     
  }
  protected Object Clone() throws CloneNotSupportedException
  {
     Object o= null;
     try
     {
     o=super.clone();
     }
     catch(CloneNotSupportedException e)
     {
      System.out.println(e.toString());
     }
     return o;
  }
}在编译的时候会出现 :
D:\Test>javac Copy.java
Copy.java:6: clone() 可以在 java.lang.Object 中访问 protected
                  CopySub test=(CopySub)sub.clone();
谢谢!

解决方案 »

  1.   

    你的clone方法写错了,把Clone改成clone,还有在main中捕获异常就可以了。没什么问题
      

  2.   

    楼上高见,怎么看了半天都没看到那个重载的方法名错了呢···
    还有就按照惯例,实现此Cloneable接口的类应该使用公共方法重写 Object.clone
    这里把clone的protected改成public是不是更好呢?
      

  3.   

    首先BS一下0分帖楼主的clone 方法是保护的,它只能被类本身或子类访问,不能被其它类访问
      

  4.   


    public class Copy {
    public static void main(String[] args) throws CloneNotSupportedException {
    CopySub sub = new CopySub("abc",18);
    CopySub test = (CopySub) sub.Clone();
    test.name = "def";
    test.age = 16;
    System.out.println("test's name is"+test.name+"    and"+"age is "+test.age);
    }
    }
    public class CopySub implements Cloneable{
    String name ;
    int age ;
    CopySub(String name,int age) {
     this.name = name ;
     this.age = age;
    }
    protected Object Clone()throws CloneNotSupportedException {
    Object o = null ;
    try{
    o = super.clone();
    }catch(CloneNotSupportedException e){
    //e.printStackTrace();
    System.out.println(e.toString());
    }
    return o ;
    }
    }
      

  5.   

    谢谢几位专家的的意见!!的确是重载 clone的方法时,写错了!
    另外想说明的是,小弟没有分数可以给!