我最近开始了 Java 编程,根据 Java SE API 文档,实现了Cloneable接口以指示允许对该类进行克隆操作。如果不是,则抛出CloneNotSupportedException 。然而,在一次练习中,我设法运行了一个程序,该程序克隆了一个没有实现 Cloneable 接口的类,并且没有引发异常。我需要知道为什么没有抛出异常。我在 Windows 7 上使用 JDK 6 update 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 ?