Java-Copy Constructors

Copy Constructors

Sometimes, we may wish to prepare a duplicate of an existing object of a class. In such situations, we have to use a special type of constructor, known as copy constructor. This constructor can take only one parameter, which is a reference to an object of the same class. In the following program, the class Data contains two variables data1 and data2, a constructor, a copy constructor and the method showData( ) to display the data1 and data2 values. Within the main( ) method of the Javaapp class, the object d1 of class Data is created by using the usual constructor. One more object of a class Data is created by using copy constructor, which takes d1 as its only argument.

Program

final


Program Source

class Data{
    
    int data1;
    int data2;
    
    Data(int d1, int d2)
    {
        data1 = d1;
        data2 = d2;
    }
    
    Data(Data obj)
    {
        data1 = obj.data1;
        data2 = obj.data2;
    }
    
    void showData()
    {
        System.out.println("Data1 :"+data1);
        System.out.println("Data2 :"+data2);
    }
}

public class Javaapp {

    public static void main(String[] args) {
       
        Data d1  = new Data(20,40);
        d1.showData();
        Data d2 = new Data(d1);
        d2.showData();
    }
}

Leave a Comment