clone (Java method)

clone (Java method)

clone() is a method in the Java programming language for object duplication. In Java, objects are manipulated through reference variables, and there is no operator for copying an object—the assignment operator duplicates the reference, not the object. The clone() method provides this missing functionality.

Contents

Overview

Classes that want copying functionality must implement some method to do so. To a certain extent that function is provided by "Object.clone()".

clone() acts like a copy constructor. Typically it calls the clone() method of its superclass to obtain the copy, etc. until it eventually reaches Object's clone() method. The special clone() method in the base class Object provides a standard mechanism for duplicating objects.

The class Object's clone() method creates and returns a copy of the object, with the same class and with all the fields having the same values. However, Object.clone() throws a CloneNotSupportedException unless the class you are trying to use it on implements the marker interface Cloneable.

The default implementation of Object.clone() performs a shallow copy. When a class desires a deep copy or some other custom behavior, they must perform that in their own clone() method after they obtain the copy from the superclass.

The syntax for calling clone in Java is (assuming obj is a variable of a class type that has a public clone() method):

Object copy = obj.clone();

or commonly

MyClass copy = (MyClass) obj.clone();

which provides the typecasting needed to assign the generic Object reference returned from clone to a reference to a MyClass object.

One disadvantage with the design of the clone() method is that the return type of clone() is Object, and needs to be explicitly cast back into the appropriate type. However, overriding clone() to return the appropriate type is preferable and eliminates the need for casting in the client (using covariant return types, since J2SE 5.0).

Another disadvantage is that one often cannot access the clone() method on an abstract type. Most interfaces and abstract classes in Java do not specify a public clone() method. As a result, often the only way to use the clone() method is if you know the actual class of an object; which is contrary to the abstraction principle of using the most generic type possible. For example, if one has a List reference in Java, one cannot invoke clone() on that reference because List specifies no public clone() method. Actual implementations of List like ArrayList and LinkedList all generally have clone() methods themselves, but it is inconvenient and bad abstraction to carry around the actual class type of an object.

Alternatives

There are alternatives to clone(), notably the use of a copy constructor - a constructor that accepts as a parameter another instance of the same class - or a factory method. These methods are not always adequate when the concrete type of the cloned object is not known in advance. (However, clone() is often not adequate either for the same reason, as most abstract classes do not implement a public clone() method.)

Also the use of serialization and deserialization is another alternative to using clone.

clone() and the Singleton pattern

When writing a class using the Singleton pattern, only one instance of that class can exist at a time. As a result, the class must not be allowed to make a clone. To prevent this, override the clone() method using the following code:

public Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException(); 
}

(Note: This is only necessary if a superclass implements a public clone() method, or to prevent a subclass from using this class's clone() method to obtain a copy. Since classes don't usually inherit a public clone() method (Object doesn't have a public clone() method), it is usually unnecessary to explicitly implement a non-functional clone() method.

clone() and class hierarchy

When working with the clone() in a hierarchy of classes, there are several things that must be handled properly.

1) Every type reference that needs to be cloned must have a clone() method in its own class or a publicly accessible clone() method in its parent classes. That means that if you want to clone a reference to an abstract base class, either the base class must have a clone() method, or one of its parents must have a publicly accessible clone() method.

Example:

since varY1 is of type Y, then Y must have clone(), or a parent of Y must have clone()

abstract public class X implements Cloneable {
        public X clone() throws CloneNotSupportedException {
                return (X) super.clone();
        }
}
 
abstract public class Y extends X { }
 
public class Z extends Y { }
 
public class test1 {
        public void function() throws CloneNotSupportedException {
                Y varY1 = new Z();
                Y varY2 = (Y) varY1.clone();
        }
}

2) Every class that has any data other than primitives that has to be cloned must contain a clone() function that handles it. This includes all objects and all primitives that are allocated with the 'new' command such as variable length arrays. (This assumes that the programmer wants the objects to be cloned (deep copy) and not just have their reference copied (shallow copy).)

Example:

since class Z has a reference to an object of another class, there needs to be specific code to clone that object.

abstract public class X implements Cloneable {
        public X clone() throws CloneNotSupportedException {
                return (X) super.clone();
        }
}
 
abstract public class Y extends X { }
 
public class ObjectABC implements Cloneable {
        public ObjectABC clone() throws CloneNotSupportedException {
                return (ObjectABC) super.clone();
        }
}
 
public class Z extends Y {
        private ObjectABC someABC;
 
        public Z clone() throws CloneNotSupportedException {
                Z newZ = (Z) super.clone();
                newZ.someABC = someABC.clone();
 
                return newZ;
        }
}
 
public class test1 {
        public void function() throws CloneNotSupportedException {
                Y varY1 = new Z();
                Y varY2 = (Y) varY1.clone();
        }
}

Easy Solution:

The easiest solution to this is to make the base class "implements Cloneable" and have the base class and all sub-classes contain the clone() method. When a class has data in it that must be cloned, adding a line or two to the clone() method is straight forward.

Example:

abstract public class X implements Cloneable {
        public X clone() throws CloneNotSupportedException {
                return (X) super.clone();
        }
}
 
abstract public class Y extends X {
        public Y clone() throws CloneNotSupportedException {
                return (Y) super.clone();
        }
}
 
public class Z extends Y {
        public Z clone() throws CloneNotSupportedException {
                return (Z) super.clone();
        }
}
 
public class test1 {
        public void function() throws CloneNotSupportedException {
                Y varY1 = new Z();
                Y varY2 = varY1.clone();
        }
}

Downsides:

If every class in your hierarchy has a clone() method, then when the actual class is cloned all of these functions will be called, adding some overhead. Over many calls this could be significant.

With complex object graphs deep copying can become problematic, with recursive references. Once one object is cloneable, others tend to follow until the entire graph attempts to implement Cloneable. Sooner or later you run into a class that you can't make Cloneable.

It is not always appropriate to have multiple copies of the same object floating around. Besides, using clone() tends to defeat the "single object, multiple references" paradigm.

clone() and final fields

Generally, clone() is incompatible with final fields. Because clone() is essentially a default constructor (one that has no arguments) it is impossible to assign a final field within a clone() method; a compiler error is the result. Where the value of the field is an immutable object this is okay; just let the 'constructor' copy the reference and both the original and its clone will share the same object.

But where the value is a mutable object it must be deep copied. The only solution is to remove the final modifier from the field, giving up the benefits the modifier conferred.

For this reason, some programmers suggest to make the objects in the hierarchy Serializable, and create copies by serializing the old object and then creating a new object from the resulting bitstream, which handles final data members correctly, but is significantly slower.[1]

External links

References

  1. ^ Java Tip 76: An alternative to the deep copy technique, JavaWorld

Wikimedia Foundation. 2010.

Игры ⚽ Нужно решить контрольную?

Look at other dictionaries:

  • Clone (Java method) — clone() is a method in the Java programming language for object duplication.Since objects in Java are manipulated through reference variables, there is no direct way to copy an object. (We would be trying to duplicate the reference variable… …   Wikipedia

  • Clone — Contents 1 Biological 2 Computing 3 Entertainment 3.1 Music …   Wikipedia

  • Clone (function) — The clone() function may be: * clone (Linux system call), in C, relating to multithreading * clone (Java method), in Java, used for object duplicationee also* Clone …   Wikipedia

  • Java — Иное название этого понятия  «Ява»; см. также другие значения. Не следует путать с JavaScript. Java Класс языка …   Википедия

  • Java syntax — The syntax of the Java programming language is a set of rules that defines how a Java program is written and interpreted. Data structuresAlthough the language has special syntax for them, arrays and strings are not primitive types: they are… …   Wikipedia

  • Java performance — Programs written in Java have had a reputation for being slower and requiring more memory than those written in natively compiled languages such as C or C++ (see e.g. [cite web url=http://www.jelovic.com/articles/why java is slow.htm title=Why… …   Wikipedia

  • Язык программирования Java — Java Класс языка: объектно ориентированный, структурный, императивный Появился в: 1995 г. Автор(ы): Sun Microsystems Последняя версия: Java Standard Edition 6 (1.6.14) Т …   Википедия

  • Comparison of Java and C++ — Programming language comparisons General comparison Basic syntax Basic instructions Arrays Associative arrays String operations …   Wikipedia

  • Template method pattern — [ LePUS3 ( [http://lepus.org.uk/ref/legend/legend.xml legend] ) ] In software engineering, the template method pattern is a design pattern.It is a so called behavioral pattern, and is unrelated to C++ templates.IntroductionIn a template pattern,… …   Wikipedia

  • Object copy — An object copy is an action in computing where a data object has its attributes copied to another object of the same data type. An object is a composite data type in object oriented programming languages. The copying of data is one of the most… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”