Confusion about cloneable interface and object.clone() in java

后端 未结 4 989
误落风尘
误落风尘 2020-12-09 16:58

If I have:

class foo implements Cloneable

and then do:

bar = new foo();
bar.clone();

I get a shallow cop

4条回答
  •  忘掉有多难
    2020-12-09 17:26

    Object.clone() has an implementation:

    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#clone()

    This link explains the Cloneable interface: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Cloneable.html

    An object must implement the Cloneable interface in order to call the clone() method, otherwise, it throws a CloneNotSupportedException.

    By definition, all classes in Java extend the base Object class, and Object class has a default clone() method, even though Object itself does not implement Cloneable. The Object class's clone() method will be called if you do not override it yourself.

提交回复
热议问题