java - CloneNotSupportedException not thrown on calling clone() method on object that does not implement Cloneable interface -
i started java programming , according java se api documentation, cloneable interface implemented indicate clone operations on class allowed. if not, clonenotsupportedexception thrown. in practice session managed run program cloned class not implement cloneable interface , no exception thrown. need know why exception not thrown. using jdk 6 update 45 , latest eclipse ide on windows 7. following code:
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 , getters 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 practiceclass's instances , returns 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 instance fields using setters pc1.setfield1(111); pc1.setfield2(222); pc1.setfield3(333); //display values screen system.out.println(pc1.getfield1()+" "+pc1.getfield2()+" "+pc1.getfield3()); //create clone of practiceclass object practiceclass pc2=pc1.clone(); //print values practiceclass clone object system.out.println(pc2.getfield1()+" "+pc2.getfield2()+" "+pc2.getfield3()); } }
this code executes without exception thrown. why isn't clonenotsupportedexception thrown?
in order clonenotsupportedexception
thrown, must call super.clone()
inside own clone()
method. method verify if class implements cloneable
Comments
Post a Comment