Copying The Values of One Object to Another Using Constructor in Java

Introduction

 
We can copy the values of one object to another using many ways like :
  1. Using clone() method of an object class.
  2. Using constructor.
  3. By assigning the values of one object to another.
in this example, we copy the values of object to another with help a constructor.
 
Example :
  1. package employee;  
  2. class Employee {  
  3.  int refno;  
  4.  String refname;  
  5.  Employee(int i, String n) {  
  6.   refno = i;  
  7.   refname = n;  
  8.  }  
  9.  Employee(Employee e) {  
  10.   refno = e.refno;  
  11.   refname = e.refname;  
  12.  }  
  13.  void display() {  
  14.   System.out.println(refno + " " + refname);  
  15.  }  
  16.  public static void main(String[] args) {  
  17.   Employee e1 = new Employee(123"raman");  
  18.   Employee e2 = new Employee(e1);  
  19.   e1.display();  
  20.   e2.display();  
  21.  }  
  22. }  
Output
 
1.jpg
 
Next Recommended Reading Copy one file to another in java