import java.util.*;
import java.lang.*;
public class Test{
public static void main(String[] argv){
String s1="abc";
String s2=(String) s1.clone();
}
}
Why this simple test program doesn't work?
Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object.
Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException. The clone() method is defined in the Object class.
The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed, so we can use object cloning.
The Java Object clone() method creates a shallow copy of the object. Here, the shallow copy means it creates a new object and copies all the fields and methods associated with the object. The syntax of the clone() method is: object.clone()
clone
is a method of the Object class. For a class to be "cloneable" it should implement the marker Cloneable
interface. String
class doesn't implement this interface and doesn't override the clone method hence the error.
I hope the above snippet is for educational purposes because you should never feel a need to call clone
on strings in Java given that:
new String(String)
which acts like a copy constructor and is pretty much equivalent to your clone()
call.Object.clone()
is protected. It is a tricky API to use.
Usually one exposes clone()
when one extends Object by broadening the method's visibility.
Clone on any string has little meaning, since it is both final
and immutable.
There is a reason to copy a string; that can be done with:
String s1 = ...;
String s2 = new String(s1)
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