按照书上的说法,只要在类声明中加入implements Cloneable就
可以调用默认的Clone()方法了。但下面的代码编译不能通过,请
帮忙看看,谢谢了。public class Cat implements Cloneable{
    public static void main(String[] args){
        Cat myCat = new Cat();
        Cat theOtherCat = (Cat)myCat.clone();
    }
}

解决方案 »

  1.   

    你没有抛出异常
    public static void main(String[] args) throws CloneNotSupportedException
      

  2.   

    clone() is a protected method in Object class, any class implements Cloneable must override super.clone() to do copy of your myCat.for example;
    public class cloneableTest
    {
       public static void main(String [] args)
       {
          Cat myCat = new Cat("Meo");
          Cat theOtherCat = myCat.clone();
          theOtherCat.say();
          }
       private static class Cat implements Cloneable
       {
          public Cat(String s)
          {
             this.s = s;
             }
          public Cat clone()
          {
             Cat cloned = new Cat(this.s);
             return cloned;
             }
          public void say()
          {
             System.out.println(this.s);
             }
          private String s;
          }
       }
      

  3.   

    output:367(6^_^)->java cloneableTest
    Meo
    368(6^_^)->
      

  4.   

    you may write clone() your Cloneable object anyway you want.for exampleyou can add into your class a boolean variable isCopy to distinguish the cloned object with the original object.
      

  5.   

    在Cat类内部重写clone方法public class Cat implements Cloneable{
      public Cat clone(){
            return super.clone();
      }
      public static void main(String[] args){
      Cat myCat = new Cat();
      Cat theOtherCat = (Cat)myCat.clone();
      }
    }
      

  6.   

    Object已经实现了Cloneable接口,只是他将clone的范围缩小了,实现新类的时候没必要再去实现Cloneable接口,只接重写clone方法就可以了,不过默认的都是protected的改成public就得了。
      

  7.   

    嗯,clone得重写,改下就好了
      

  8.   

    Object的clone()方法抛出了CloneNotSupportedException异常,所以你调用clone()时要捕获或者同样在方法处声明throws CloneNotSupportedException