public class test implements Cloneable {
@Override
public test clone() {
return (test) super.clone();
}
public static void main(String[] args) {
new test().clone();
}
}
I get error: unreported exception CloneNotSupportedException
when I try to compile this (at line 4, not the main). As far as I can tell, the entire purpose of implementing Cloneable
is to get rid of the exception.
super.clone()
without throwing or catching the exception?To avoid the CloneNotSupportedException , the Cloneable interface should be implemented by the class whose objects need to be cloned. This indicates to the Object. clone() method that it is legal to create a clone of that class and helps avoid the CloneNotSupportedException .
A class must implement the Cloneable interface if we want to create the clone of the class object. The clone() method of the Object class is used to create the clone of the object. However, if the class doesn't support the cloneable interface, then the clone() method generates the CloneNotSupportedException.
Cloneable interface is implemented by a class to make Object. clone() method valid thereby making field-for-field copy. This interface allows the implementing class to have its objects to be cloned instead of using a new operator.
To clone a list, one can iterate through the original list and use the clone method to copy all the list elements and use the add method to append them to the list. Approach: Create a cloneable class, which has the clone method overridden. Create a list of the class objects from an array using the asList method.
Is there a way to use super.clone() without throwing or catching the exception?
No because Object#clone()
(the method you are calling with super.clone()
) declares it.
Does the interface actually do anything?
Yes, but very little: if you don't implement it, Object#clone()
will actually throw the declared exception.
You need to handle CloneNotSupportedException
exception, Class name should be start with capital letter.
Is there a way to use super.clone() without throwing or catching the exception?
If you don't want to handle exception inside clone
method then use throws
keyword it will propagate your exception to called method.
public class Test implements Cloneable {
@Override
public Test clone() throws CloneNotSupportedException{
return (Test) super.clone();
}
public static void main(String[] args) {
try {
new Test().clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
Does the interface actually do anything?
public interface Cloneable
A class implements the Cloneable
interface to indicate to the Object.clone()
method that it is legal for that method to make a field-for-field copy of instances of that class. read more
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With