In this Example we are going to understanding the clone in Java and its exceptons..
Error Message :
Exception in thread "main" java.lang.CloneNotSupportedException: com.si.cloneSample
at java.base/java.lang.Object.clone(Native Method)
at com.si.cloneSample.main(cloneSample.java:15)
Error Description :
package com.si;
public class cloneSample {
int number;
Integer[] intArray;
cloneSample(int num){
number = num;
intArray= new Integer[number];
}
public static void main(String[] args) throws CloneNotSupportedException {
cloneSample samp1 = new cloneSample(15);
cloneSample copy = (cloneSample) samp1.clone();
samp1.intArray[0]= 1;
System.out.println(samp1.intArray[0]);
}
}
In the above example ,the red background color line is giving the exception.
Clone the object wont happen if that object is not implementing the Cloneable.
Solution:
To avoid this exception we should implements the Cloneable interface all the time while doing the cloning process.
package com.si;
public class cloneSample implements Cloneable {
int number;
Integer[] intArray;
cloneSample(int num){
number = num;
intArray= new Integer[number];
}
public static void main(String[] args) throws CloneNotSupportedException {
cloneSample samp1 = new cloneSample(15);
cloneSample copy = (cloneSample) samp1.clone();
samp1.intArray[0]= 1;
System.out.println(samp1.intArray[0]);
}
}
Output:
1
Post a comment
Please share your valuable feedback and share this article in social media.