Share & learn

Through Innovative Digital Library

What is clone method in Java ?

Explain about clone() method in Java.
 



Answers

Posted by Paul on April 27th 2018 13:25 PM

clone() method in Java : The process of creating same copy of an object is known as cloning. It creates a new instance of the class of current object and initializes all its fields with exactly the contents of the corresponding fields of this object. - The class whose object’s copy is to be made must have a public clone method in it or in one of its parent class. - Every class that implements clone() should call super.clone() to obtain the cloned object reference. - The class must also implement java.lang.Cloneable interface whose object clone we want to create otherwise it will throw CloneNotSupportedException when clone method is called on that class’s object. Syntax of clone() method : protected Object clone() throws CloneNotSupportedException Here is the code to implement clone() method :

// Java program to implement clone() method

class Test {
    
int xy;
}

class 
Test2 implements Cloneable {
    
int a;
    
int b;
    
Test c = new Test();

    public 
Object clone() throws CloneNotSupportedException {
        return 
super.clone();
    }
}

// Driver class
public class CloningDemo {
    public static 
void main(String args[]) throws CloneNotSupportedException {
        
Test2 obj1 = new Test2();
        
obj1.10;
        
obj1.20;
        
obj1.c.30;
        
obj1.c.40;

        
Test2 obj2 = (Test2obj1.clone();

        
// Creating a copy of object obj1 and passing
        // it to obj2
        
obj2.100;

        
// Change in primitive type of obj2 will not
        // be reflected in obj1 field
        
obj2.c.300;

        
// Change in object type field will be
        // reflected in both obj2 and obj1(shallow copy)
        
System.out.println(obj1." " obj1." " obj1.c." " obj1.c.y);
        
System.out.println(obj2." " obj2." " obj2.c." " obj2.c.y);
    }
}
Answer Question

Your email address will not be published. Required fields are marked *

  • Minimum 20 character
D0XQ

related questions

Most liked questions

Most answered questions

Login
D0XQ Refresh
Register
D0XQ Refresh
Forgot password
Ask a Question
Minimum 20 character
Minimum 20 character
Reply
Minimum 20 character
D0XQ Refresh