Search Your Topic

config
Thursday, 13 July 2017 11:04

Object Cloning in Java

Written by
Rate this item
(0 votes)

The object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object.

The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.

The clone() method is defined in the Object class. Syntax of the clone() method is as follows:

 
  1. protected Object clone() throws CloneNotSupportedException  

Why use clone() method ?

The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed that is why we use object cloning.

Advantage of Object cloning

Example of clone() method (Object cloning)

Let's see the simple example of object cloning

 
  1. class Student18 implements Cloneable{  
  2. int rollno;  
  3. String name;  
  4.   
  5. Student18(int rollno,String name){  
  6. this.rollno=rollno;  
  7. this.name=name;  
  8. }  
  9.   
  10. public Object clone()throws CloneNotSupportedException{  
  11. return super.clone();  
  12. }  
  13.   
  14. public static void main(String args[]){  
  15. try{  
  16. Student18 s1=new Student18(101,"amit");  
  17.   
  18. Student18 s2=(Student18)s1.clone();  
  19.   
  20. System.out.println(s1.rollno+" "+s1.name);  
  21. System.out.println(s2.rollno+" "+s2.name);  
  22.   
  23. }catch(CloneNotSupportedException c){}  
  24.   
  25. }  
  26. }  
Output:101 amit
       101 amit

Read 49 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.

Java Training

Facebook