Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (6.1k points)
Can anybody tell me what is copy constructor in Java?

1 Answer

0 votes
by (11.7k points)
edited by

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

Java does not provide an explicit copy constructor, the user needs to define itself.

Code:

import java.util.Scanner;

public class Employee {

   private String name;

   private int age;

   public Employee(String name, int age){

      this.name = name;

      this.age = age;

   }

   public Employee(Employee 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();

      Employee std = new Employee(name, age);

      System.out.println("Contents of the original object");

      std.displayData();

      System.out.println("Contents of the copied object");

      Employee copyOfStd = new Employee(std);

      copyOfStd.displayData();

   }

}

Here,  a copy constructor is created which accepts an object of the current class and initializes the values of instance variables with the values in the obtained object. If a user creates an object and invokes the copy constructor bypassing it, an earlier created copy of the object is given to the user.

Related questions

0 votes
1 answer
asked Feb 11, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Apr 3, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Feb 20, 2021 in Java by Jake (7k points)
0 votes
1 answer
asked Feb 15, 2021 in Java by Jake (7k points)

Browse Categories

...