MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to implement cloning in java using Cloneable interface?

The java cloning mechanism is used when we need exact copy of an object. In this article, we will discuss and explore most of the important aspects of java cloning.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

Introduction:

The Cloneable interface in java is a marker interface. It does have any method. But if we write a class as below, it gives a message to the jvm that the class can be cloned. The following code shows a simple object cloning process.

The Cloneable interface does not have any members. The interface is used to indicate that a class (which implements the interface) allows a bitwise copy of an object, known as cloning. An exception known as 'CloneNotSupportedException' is thrown if clone () is called on a class which does not implement Cloneable interface. In a cloning process the constructor of the object is not called. So cloning can be defined as an exact copy of the original object.

Listing 1: Sample class implements Cloneable interface

package com.home.cloning;

public class CloneClass implements Cloneable {
	int a;
	double b;

	// This method calls Object's clone().
	CloneClass getClone() {
		try {
			// call clone in Object.
			return (CloneClass) super.clone();
		} catch (CloneNotSupportedException e) {
			System.out.println (" Cloning not allowed. " );
			return this;
		}
	}
}

Listing 2: Sample class showing cloning of objects

package com.home.cloning;

public class TestCloneObject {

	public void testIface() {
		CloneClass x1 = new CloneClass();
		CloneClass x2;
		x1.a = 15;
		x1.b = 35.05;
		x2 = x1.getClone(); // clone x1
		System.out.println(" x1: " + x1.a + " " + x1.b);
		System.out.println(" x2: " + x2.a + " " + x2.b);
	}

	public static void main(String args[]) {
		TestCloneObject testCloneObject = new TestCloneObject();
		// test via protected
		testCloneObject.testIface();
	} 

}

In the above example, the method getClone calls the clone method in the object and returns the object. It must be noticed here that the object with is returned after the cloning mechanism has to be type casted into its appropriate type, in this case it is CloneClass

If the class is not implementing the cloneable interface, and we try to clone that object we get a CloneNotSupportedException . In the process of cloning, the constructor is not called rather an exact copy of the said object is created. But the object of which the clone is created, must implement the cloneable interface.

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 object is an instance of a class that implements the marker interface Cloneable.

The default implementation of Object.clone () performs a shallow copy. If a class requires a deep copy or some other custom behavior, it must have its customized clone () method after they obtain the copy from the super class.

Advantages of cloning:

Cloning mechanism saves extra task of the developer in case we need to create a copy of an object. We do not need to call the new operator of the object. Thus cloning saves a lot of extra processing tasks of developer. A clone of an object is an exact copy of the object.

Disadvantages of cloning:

One disadvantage of cloning is that the return type of the clone method is an Object. Hence a type casting is required on the created object.

Another disadvantage is that it is not possible to access the clone method on an abstract type. Most interfaces and abstract classes in Java do not have to specify a public clone method. As a result, the clone method is used only if the actual class of an object is known which is against the abstraction principle of using the most generic type possible. For example, if one has a List reference in Java, one cannot invoke clone method 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.

Cloning is a potentially dangerous action, as it can have some unintended side effects. e.g., if the object being cloned contains a reference variable say refObject, then in the cloned object, refObject will have the reference of the same object which the original object is referring to. If the clone makes a change in the contents of the refObject, then the change will be reflected in the original object as well. Consider the following example - If an object opens an I/O stream and is then cloned, then both of the two objects will be capable of operating on the same stream. Further, if one of these objects closes the stream, then the stream is closed for both and if the second object tries to write to it, this causes an error.

Since cloning can cause some problems, the clone method. So the clone method should be called from within a class which is implementing the cloneable interface where the method calling the clone method is made protected, or it must be explicitly overridden by the class which is public. In the example above we have seen cloning by making the clone protected. The following example illustrates the cloning methodology via overriding:

Listing 3: Sample class implements Cloneable interface

package com.home.cloning;

public class CloneViaOverRiding implements Cloneable {
	int a;
	double b;

	// clone() is now overridden and is public.
	public Object clone() {
		try {
			// call clone in Object.
			return super.clone();
		} catch (CloneNotSupportedException e) {
			System.out.println("Cloning not allowed.");
			return this;
		}
	}
}

Listing 4: Sample class implements cloning using method overriding

package com.home.cloning;

public class TestCloneObject {

	public void testPublic() {
		CloneViaOverRiding x1 = new CloneViaOverRiding();
		CloneViaOverRiding x2;
		x1.a = 10;
		x1.b = 20.98;
		// here, clone() is called directly.
		x2 = (CloneViaOverRiding) x1. clone ();
		System.out.println("x1: " + x1.a + " " + x1.b);
		System.out.println("x2: " + x2.a + " " + x2.b);
	}

	public static void main(String args[]) {
		TestCloneObject testCloneObject = new TestCloneObject();
				
		// test via public
		testCloneObject.testPublic();
	}
}

In this example the method, the method clone of the object class is overridden that is why it is declared public in contrast to the earlier example, where the getClone does not have any access modifiers making it accessible only at the package level.

In either of these two approaches, implementing the cloneable interface is mandatory.

The side effects caused by cloning are sometimes difficult to identify in the initial level. It is easy to think that a class is safe for cloning when it actually is not. In general, is not advised to implement the Cloneable interface for any class without having a solid business ground.

Alternative to cloning:

Cloning mechanism has few alternatives:

  • Copy constructor - a copy constructor is a constructor which accepts another instance of the same class as a parameter.
  • Factory method - these methods are not always adequate when the concrete type of the cloned object is not known in advance.
  • Use of serialization and deserialization is another alternative to using clone.

Conclusion:

  • Object cloning is the mechanism of creating a copy of an existing object
  • Cloning follows the shallow copy mechanism
  • Closing saves some extra tasks of the developer
  • Once the cloning is done the created clone object is required to explicitly casted in to the required type
  • Cloning has some side effects e.g. if an object which is cloned has a reference to another object, and the new cloned object modifies the object which being referenced, then the original object also gets changed.
  • Cloning mechanism has some alternatives - the copy constructor, factory method, serialization and deserialization.


Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login