Duplicating Objects using a Constructor in Java


A copy constructor can be used to duplicate an object in Java. The copy constructor takes a single parameter i.e. the object of the same class that is to be copied. However, the copy constructor can only be explicitly created by the programmer as there is no default copy constructor provided by Java.

A program that demonstrates this is given as follows −

Example

 Live Demo

class NumberValue {
   private int num;
   public NumberValue(int n) {
      num = n;
   }
   public NumberValue(NumberValue obj) {
      num = obj.num;
   }
   public void display() {
      System.out.println("The number is: " + num);
   }
}
public class Demo {
   public static void main(String[] args) {
      NumberValue obj1 = new NumberValue(12);
      NumberValue obj2 = new NumberValue(obj1);
      obj1.display();
      obj2.display();
   }
}

Output

The number is: 12
The number is: 12

Now let us understand the above program.

The NumberValue class is created with a data member num and single member function display() that displays the value of num. There are two constructors in class NumberValue where one of these takes a single parameter of type int and another is a copy constructor that takes a single parameter i.e. an object of class NumberValue. A code snippet which demonstrates this is as follows −

class NumberValue {
   private int num;
   public NumberValue(int n) {
      num = n;
   }
   public NumberValue(NumberValue obj) {
      num = obj.num;
   }
   public void display() {
      System.out.println("The number is: " + num);
   }
}

In the main() method, objects obj1 and obj2 of class NumberValue are created and the display() method is called for both of them. A code snippet which demonstrates this is as follows −

public class Demo {
   public static void main(String[] args) {
      NumberValue obj1 = new NumberValue(12);
      NumberValue obj2 = new NumberValue(obj1);
      obj1.display();
      obj2.display();
   }
}

Updated on: 30-Jun-2020

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements