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 object class.
  2. Using constructor.
  3. By assigning the values of one object to another.

In this example we copy the values of one object to another with the help of constructor.

Example :

package employee;

class Employee

{

    int refno;

    String refname;
    Employee(
int i, String n)
    {

        refno = i;

        refname = n;

    }

    Employee(Employee e)

    {

        refno = e.refno;

        refname = e.refname;

    }

   
void display()
    {

        System.
out.println(refno+" "+refname);
    }
 
   
public static void main(String[] args)
    {

         Employee e1 =
new Employee(123,"raman");
        Employee e2 =
new Employee(e1);
        e1.display();

        e2.display();
 
    }

}


Output

1.jpg

Ebook Download
View all
Learn
View all