Copy Constructor in Java


A copy constructor is a constructor that creates a new object using an existing object of the same class and initializes each instance variable of newly created object with corresponding instance variables of the existing object passed as argument.

Syntax :
   public class_Name(const className old_object)

Example :
   Public student(student o)

The class CopyConstructor contains two constructors - one is a parameterized constructor that initializes the age and name instance variables of the class. The other constructor is the copy constructor that takes an object of the same class as a parameter and initializes its own instance variables with the values of the instance variables of the parameter object.

The display() method is used to display the name and age values. In the main() method, the user is prompted to enter their name and age, which are used to create an object cc of the CopyConstructor class using the parameterized constructor. A second object c2 is then created using the copy constructor, which takes the object cc as a parameter. Finally, the display() method is called on both objects to display the name and age values.

Source Code

import java.util.Scanner;
class CopyConstructor
{
	int age;
	String name;
	CopyConstructor(int a,String n)
	{
		age=a;
		name=n;
	}
	CopyConstructor(CopyConstructor cc)
	{
		age=cc.age;
		name=cc.name;
	}
	void display()
	{
		System.out.println("Your name is : "+name + "\nAge is : "+age);
	}
	public static void main(String[] arg)
	{
		System.out.print("Enter your name and age :");
		Scanner scan  = new Scanner(System.in);
		String name =scan.nextLine();
		int age =scan.nextInt();
		CopyConstructor cc = new CopyConstructor(age,name);
		CopyConstructor c2=new CopyConstructor(cc);
		cc.display();
		c2.display();
	}
}

Output

Enter your name and age :Tutor Joes
27
Your name is : Tutor Joes
Age is : 27
Your name is : Tutor Joes
Age is : 27
To download raw file Click Here

Basic Programs