Wednesday, 10 January 2018

Copy Constructor in Java

Tags


Unlike C++, Java doesn't support default copy constructor, But you can write your own copy constructor in Java. Java program to explain the copy constructor is given below.

Example:

import java.util.*;
import java.lang.*;

class employee{
 
      private int salary;
      private String post;

      public employee(int salary,String post){

         this.salary=salary;
         this.post=post;

      }

      public employee(employee emp){
         this.salary=emp.salary;
         this.post=emp.post;
      }

      
      public String print(){

          return salary+" "+post;
      }

}
public class copyconstructor{

   public static void main(String args[]){

       Scanner in=new Scanner(System.in);
       System.out.println("\nEnter the salary of the employee: \n");
       int salary=in.nextInt();
       System.out.println("\nEnter the post of the employee: \n");
       String post=in.next();

       employee emp1=new employee(salary,post);

       //calling the copy constructor
       employee emp2=new employee(emp1);

       System.out.println("\n\nDetails of the employee 1: "+emp1.print());
       System.out.println("\n\nDetails of the employee 2: "+emp2.print());
   }
}


Output:



EmoticonEmoticon