Copy Assignment Operator Sub Class In Java

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.

Overview[edit]

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

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

The class's method creates and returns a copy of the object, with the same class and with all the fields having the same values. However, throws a unless the object is an instance of a class that implements the marker interface.

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

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

Objectcopy=obj.clone();

or commonly

MyClasscopy=(MyClass)obj.clone();

which provides the typecasting needed to assign the general reference returned from to a reference to a object.

One disadvantage with the design of the method is that the return type of is , and needs to be explicitly cast back into the appropriate type. However, overriding 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 method on an abstract type. Most interfaces and abstract classes in Java do not specify a public method. As a result, often the method can only be used if the actual class of an object is known, which is contrary to the abstraction principle of using the most generic type possible. For example, if one has a reference in Java, one cannot invoke on that reference because specifies no public method. Actual implementations of like and all generally have methods themselves, but it is inconvenient and bad abstraction to carry around the actual class type of an object.

Alternatives[edit]

There are alternatives to , 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, is often not adequate either for the same reason, as most abstract classes do not implement a public method.)

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

and the Singleton pattern[edit]

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, one can override the method using the following code:

publicObjectclone()throwsCloneNotSupportedException{thrownewCloneNotSupportedException();}

This is only necessary if a superclass implements a public method, or to prevent a subclass from using this class's method to obtain a copy. Classes don't usually inherit a public method because doesn't have a public method, so it is usually unnecessary to explicitly implement a non-functional method.

and class hierarchy[edit]

To provide a properly cloneable object of any type, the clone() method must be both declared correctly and implemented correctly according to the convention described in Object.clone().

1) Every type that needs to be cloned must have a public clone() method in its own class or a publicly accessible clone() method in one of its parent classes.

Example:

To invoke clone() on varY1, which is of type Y, then Y or a parent of Y must declare a publicly accessible clone() method. Here, it is the parent class X that provides the public clone() method.

publicclassXimplementsCloneable{publicXclone()throwsCloneNotSupportedException{return(X)super.clone();}}publicclassYextendsX{}publicclassZextendsY{}publicclasstest1{publicvoidfunction()throwsCloneNotSupportedException{YvarY1=newZ();YvarY2=(Y)varY1.clone();}}

2) Every class that implements clone() should call super.clone() to obtain the cloned object reference. If the class has any object references that must be cloned as well (when deep copying, for example), then the clone() method should perform any required modifications on the object before returning it. (Since Object.clone() returns an exact copy of the original object, any mutable fields such as collections and arrays would be shared between the original and the copy - which in most cases would neither be expected nor desired.)

Example:

Since class Z contains an object reference, its clone() method also clones that object reference in order to return a deep copy of the original.

publicclassXimplementsCloneable{publicXclone()throwsCloneNotSupportedException{return(X)super.clone();}}publicclassYextendsX{}publicclassObjectABCimplementsCloneable{publicObjectABCclone()throwsCloneNotSupportedException{return(ObjectABC)super.clone();}}publicclassZextendsY{privateObjectABCsomeABC;publicZclone()throwsCloneNotSupportedException{ZnewZ=(Z)super.clone();newZ.someABC=someABC.clone();returnnewZ;}}publicclasstest1{publicvoidfunction()throwsCloneNotSupportedException{YvarY1=newZ();YvarY2=(Y)varY1.clone();}}

Potential Pitfalls[edit]

If every class in a hierarchy implements a clone() method, all of these functions will be called upon cloning, adding some overhead. Over many iterations, this overhead could become significant.

With complex object graphs, deep copying can also become problematic when recursive references exist.

It is not always appropriate to have multiple copies of the same object floating around. If the purpose of a specific clone() implementation is not fully understood by consumers, it may unintentionally break the "single object, multiple references" paradigm.

and fields[edit]

Generally, is incompatible with fields. Because is essentially a default constructor (one that has no arguments) it is impossible to assign a field within a 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. One solution is to remove the 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]

Alternatively, one can return a completely new object from the current objects fields, which can be done first calling the constructor, and later assigning non final fields. Another alternative method is actually making the idea formal : creating a copy constructor that takes an instance. In fact that is what is recommended over clone by some people. [2]

External links[edit]

References[edit]

Polymorphism refers to the fact that different objects can respond to the same method in different ways, depending on the actual type of the object. This can occur because a method can be overridden in a subclass. In that case, objects belonging to the subclass will respond to the method differently from objects belonging to the superclass.

(Note: If B is a subclass of A, then a variable of type A can refer to either an object of type A or an object of type B. Let's say that var is such a variable and that action() is a method in class A that is redefined in class B. Consider the statement "var.action()". Does this execute the method from class A or the method from class B? The answer is that there is no way to tell! The answer depends on what type of object var refers to, a class A object or a class B object. The method executed by var.action() depends on the actual type of the object that var refers to, not on the type of the variable var. This is the real meaning of polymorphism.)

Categories: 1

0 Replies to “Copy Assignment Operator Sub Class In Java”

Leave a comment

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *