Friday 15 June 2018

Clone() method in Java


Clone() method in Java

In Java, a new object is created from a defined class by using the new operator. The new operator creates a new object from a specified class and returns a reference to that object. In order to create a new object of a certain type, we must immediately follow our use of the new operator by a call to a constructor for that type of object.

when calling the new operator in java on a class type causes three events to be occurs:
1.New object is dynamically allocated in memory ,but all variables are initialised to standard default values.
The default values are null for object variables and 0 for all base types except Boolean variables .
2.The constructor for the new object is called with the parameters specified. The constructor fills in meaningful values for the instance variables and performs any additional computations that must be done to create this object.
3.After the constructor returns, the new operator returns a reference to the newly created object. If the expression is in the form of an assignment statement, then this address is stored in the object variable, so the object variable refers to this newly created object.
Using a correct  Operator to create copy of reference variable
In Java, there is no operator to create copy of an object. Unlike C++, in Java, if we use assignment operator then it will create a copy of reference variable and not the object. This can be explained by taking an example. Following program demonstrates the same.

// Java program to demonstrate that assignment
// operator only creates a new reference to same
// object.
import java.io.*;

// A MyClass class whose objects are cloned
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javasample;

/**
 *
 * @author rajesh kumar shukla
 */
public class MyClass {
     int x, y;
    MyClass()
    {
        x = 30;
        y = 40;
    }
}
// Driver Class
class Main
{
    public static void main(String[] args)
    {
         MyClass ob1 = new MyClass();

         System.out.println(ob1.x + " " + ob1.y);

         // Creating a new reference variable ob2
         // pointing to same address as ob1
         MyClass ob2 = ob1;

         // Any change made in ob2 will be reflected
         // in ob1
         ob2.x = 100;

         System.out.println(ob1.x+" "+ob1.y);
         System.out.println(ob2.x+" "+ob2.y);
    }
}
//output of this program
run:
30 40
100 40
100 40
BUILD SUCCESSFUL (total time: 0 seconds)

0 comments:

Post a Comment