Java – what’s the point of a clonable interface?

What's the point of a clonable interface in Java? The core object in Java has a clone () method Can you override that method

@Override
public Foo clone(){
    return new Foo(this.x,this.y);
}

Please explain why you want to use this interface I already know the details of the cloned object I just don't understand why you use this interface

Solution

To answer the first question, you must implement the clonable interface to make the clone () method work, because the clone of the object will check whether the interface has been implemented, otherwise an exception will be thrown

Using clone () is a bad idea This was one of the first unsuccessful ideas in Java There are some design problems, including that it is usually a shallow copy If you want to make a copy or deep copy of an object, you'd better create a copy constructor or copy method instead of cloning It is difficult to use clone () correctly

If you really want to use clone (), read this blog post, which describes how to use clone () When using clone (), you should basically remember five points:

1) The clone method is used to create a copy of an object in Java In order to use the clone () method, the class must implement Java Lang. clonable interface and from Java Lang. object overrides the protected clone() method If the class does not implement the clonable interface, calling the clone () method will result in clonnotsupportedexception

2) When cloning an object in Java, the constructor is not called

3) The default implementation of the clone () method in Java provides a "shallow copy" of the object, because it creates a copy of the object by creating a new instance and then assigning the copy content, which means that if your class contains a variable field, the two original objects and clone will reference the same internal object This can be dangerous because any changes made to the mutable field will be reflected in the original and copied objects To avoid this, override the clone () method to provide a deep copy of the object

4) By convention, you should call super The clone () method obtains a clone of the instance, which will help to preserve the invariant of the object created by the clone () method, that is, clone= Original and clone getClass()== original. Getclass() Although these are not absolute requirements mentioned in Javadoc

5) The shallow copy of the instance is good until it contains only primitives and immutable objects. Otherwise, you need to modify super The variable field of one or more objects returned by clone and then returned to the caller

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>