Jul 10, 2015

Copying The Values of One Object to Another


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.


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(); 
    }
}

No comments:

Post a Comment