What are copy constructors in Java?

Java 8Object Oriented ProgrammingProgramming

Generally, the copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously.

Java supports for copy constructors but unlike C language, Java does not provide an explicit copy constructor you need to define it yourself.

writing a copy constructor

Usually, to initialize the values of instance variables of a class (one way) we create a parameterized constructor accepting the values for all instance variables and initialize them with the given values.

int name;
int age;
public Student(String name, int age){
   this.name = name;
   this.age = age;
}

But, in a copy constructor accept an object of the current class and initialize the values of instance variables with the values in the obtained object.

public Student(Student std){
   this.name = std.name;
   this.age = std.age;
}

Then from the if you create an object and invoke the copy constructor by passing it, you will get a copy of the object you have created earlier.

Student std = new Student("nameValue", ageValue);
Student copyOfStd = new Student(std);

Example

Following is an example demonstrating the copy constructors in Java.

 Live Demo

import java.util.Scanner;
public class Student {
   private String name;
   private int age;
   public Student(String name, int age){
      this.name = name;
      this.age = age;
   }
   public Student(Student std){
      this.name = std.name;
      this.age = std.age;
   }
   public void displayData(){
      System.out.println("Name : "+this.name);
      System.out.println("Age : "+this.age);
   }
   public static void main(String[] args) {
      Scanner sc =new Scanner(System.in);
      System.out.println("Enter your name ");
      String name = sc.next();
      System.out.println("Enter your age ");
      int age = sc.nextInt();
      Student std = new Student(name, age);
      System.out.println("Contents of the original object");
      std.displayData();
      System.out.println("Contents of the copied object");
      Student copyOfStd = new Student(std);
      copyOfStd.displayData();
   }
}

Output

Enter your name
Krishna
Enter your age
20
Contents of the original object
Name : Krishna
Age : 20
Contents of the copied object
Name : Krishna
Age : 20
raja
Published on 08-Jul-2019 15:32:34
Advertisements