Write a Java program to Implement copy constructor


The Demo class has two instance variables, num1 and num2, which are set by a parameterized constructor that takes two integer arguments. The Demo class also has a copy constructor that takes an object of the same class as an argument. This copy constructor creates a new object with the same values for num1 and num2 as the object that is passed in as an argument.

The main method creates two objects of the Demo class, o1 and o2. The o1 object is created using the parameterized constructor, with num1 set to 10 and num2 set to 15. The o2 object is created using the copy constructor and is passed the o1 object as an argument.

Then, the printValues method is called on both objects to print the values of num1 and num2. Finally, the println statement is used to print "Copy Constructor.." to indicate that the o2 object was created using the copy constructor.

Source Code

class Copy_Constructor
{
	public static void main(String args[])
	{
		Demo o1 = new Demo(10, 15);
		Demo o2 = new Demo(o1);
 
		o1.printValues();
		System.out.println("Copy Constructor..");
		o2.printValues();
	}
}
class Demo
{
	int num1;
	int num2;
 
	Demo(int n1, int n2)
	{
		this.num1 = n1;
		this.num2 = n2;
	}
 
	Demo(Demo obj)
	{
		this.num1 = obj.num1;
		this.num2 = obj.num2;
	}
 
	void printValues()
	{
		System.out.println("Number 1 : " + num1);
		System.out.println("Number 2 : " + num2);
	}
}

Output

Number 1 : 10
Number 2 : 15
Copy Constructor..
Number 1 : 10
Number 2 : 15