对未实现Cloneable接口的对象调用clone()方法时未引发CloneNotSupportedException



我最近开始了Java编程,根据Java SE API文档,实现了可克隆接口,以指示允许在该类上进行克隆操作。如果不是,则抛出CloneNotSupportedException。然而,在一次练习中,我成功地运行了一个程序,该程序克隆了一个不实现可克隆接口的类,并且没有引发异常。我需要知道为什么没有抛出异常。我在Windows7上使用JDK6更新45和最新的Eclipse IDE。以下是代码:

package com.warren.project.first;
public class PracticeClass {
   //explicit initialisation of PracticeClass Instance Variables
   private int fieldOne=1;
   private int fieldTwo=2;
   private int fieldThree=3;
   //setters and getters for instance fields of PracticeClass
   public void setField1(int field1){
     this.fieldOne=field1;
   }
   public void setField2(int field2){
     this.fieldTwo=field2;
   }
   public void setField3(int field3){
     this.fieldThree=field3;
   }
   public int getField1(){
     return this.fieldOne;
   }
   public int getField2(){
     return this.fieldTwo;
   }
   public int getField3(){
     return this.fieldThree;
   }

   //This method clones the PracticeClass's instances and returns the clone
   @Override
   public PracticeClass clone(){
      PracticeClass practiceClass= this;
      return practiceClass;
   }
}

package com.warren.project.first;
public class AppMain {
  public static void main(String[] args) {      
    //Create PracticeClass Object
    PracticeClass pc1=new PracticeClass();
    //Set its instance fields using setters
    pc1.setField1(111);
    pc1.setField2(222);
    pc1.setField3(333);
    //Display Values to screen
    System.out.println(pc1.getField1()+" "+pc1.getField2()+" "+pc1.getField3());
    //Create clone of PracticeClass object
    PracticeClass pc2=pc1.clone();
    //Print values from PracticeClass clone object
    System.out.println(pc2.getField1()+" "+pc2.getField2()+" "+pc2.getField3());
  }
}

此代码成功执行,没有引发任何异常。为什么不抛出CloneNotSupportedException

为了抛出CloneNotSupportedException,必须在自己的clone()方法内调用super.clone()。此方法将验证您的类是否实现Cloneable

相关内容

最新更新