Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java Object Cloning

Cloning means creating a copy of the object. There is a way that we can create an exact copy of an object which is known as object cloning. To clone an object we use clone() method which is coming from Object class. Here we have to implement Clonable interface by the class whose object clone we want to create. If we are not trying to implement Cloneable interface, clone() method generates CloneNotSupportedException.
Let's see demo program on objet clonig for better clarity.

Example

class Employee implements Cloneable
{ 
	int id; 
	String name;  
										  
	Employee(int id,String name) 
	{  
		this.id=id;
		this.name=name; 
	} 									  
	public Object clone()throws CloneNotSupportedException
	{   
		return super.clone();  
	}  									  
	public static void main(String[] args)
	{ 
		try 
		{   
			Employee e1=new Student18(102,"Trilochan");
			Employee e2=(Employee)e1.clone();
			System.out.println(e1.id+" "+e1.name); 
			System.out.println(e2.id+" "+e2.name);
		} 
		catch(CloneNotSupportedException 
		{
															
		}
	} 
}

Output

As you can see in the above example, both reference variables have the same value. Thus, the clone() copies the values of an object to another. So we don't need to write explicit code to copy the value of an object to another. If we create another object by new keyword and assign the values of another object to this one, it will require a lot of processing on this object. So to save the extra processing task we use clone() method.

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext