user1192813
user1192813

Reputation: 71

Clone() in java

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?

Upvotes: 7

Views: 24443

Answers (5)

VicXj
VicXj

Reputation: 203

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.

protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object.

Strings in Java are immutable. Feel free to share them across methods/classes There already exists a constructor new String(String) which acts like a copy constructor and is pretty much equivalent to your clone() call.

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.

Upvotes: 0

Sanjay T. Sharma
Sanjay T. Sharma

Reputation: 23208

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:

  1. Strings in Java are immutable. Feel free to share them across methods/classes
  2. There already exists a constructor new String(String) which acts like a copy constructor and is pretty much equivalent to your clone() call.

Upvotes: 20

user381105
user381105

Reputation:

It obviously couldn't be compiled. Object.clone has protected access.

Beyond being accessible within the class itself and to code within the same package..., a protected member can also be accessed from a class through object references that are of at least the same type as the class

Upvotes: 1

driangle
driangle

Reputation: 11779

clone() is a protected method on the Object class. If you want a class to be cloneable the general pattern is to implement Cloneable and make that method public.

Upvotes: 1

Dilum Ranatunga
Dilum Ranatunga

Reputation: 13374

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)

Upvotes: 6

Related Questions