What is a copy constructor in Java?

In Java, a copy constructor is a constructor that takes an object of the same class as a parameter and copies each field of the class to the new object. It returns a duplicate copy of the existing object of the class.

The copy constructor is called when a single object reference of the same class is passed as an argument. The copy constructor generates the deep copy of the heavy objects.

In Java, the compiler does not create any copy constructor by default. A copy constructor also does not have a return type.

The syntax is

Student n = new Student();
Student n2 = new Student(n);

n2 makes a call to the copy constructor defined in the class.

public class Student {
  int a = 10;
  int b = 20;
  public Student() {}
  // Declaring a copy constructor 
  public Student(Student n) {
    a = n.a;
    b = n.b;
  }
  public static void main(String[] args) {
    Student n = new Student();
    System.out.println("Value of a: " + n.a);
    System.out.println("Value of b: " + n.b);
    // Calling a copy constructor
    Student n2 = new Student(n);
    System.out.println("Value of a in copy constrcutor: " + n2.a);
    System.out.println("Value of b in copy constructor: " + n2.b);
  }
}

The output is

Value of a: 10
Value of b: 20
Value of a in copy constrcutor: 10
Value of b in copy constructor: 20
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions