Clone() in java

风格不统一 提交于 2021-02-04 05:41:48

问题


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?


回答1:


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.



回答2:


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)



回答3:


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.




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/9164107/clone-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!