Shallow Copy Object Cloning in Java


This Java program demonstrates object cloning. The program defines two classes: Designation and Employee. The Designation class has a single instance variable role which represents an employee's job title. The Employee class has three instance variables: name, age, and deg (an object of the Designation class). It also has two methods: display() and clone().

The display() method simply prints the employee's name, age, and job title to the console. The clone() method is used to create a copy of an Employee object. It implements the Cloneable interface and overrides the clone() method from the Object class. The method returns an object of type Object, so it must be cast to an Employee object after calling the clone() method.

In the main() method, an instance of Employee class is created and its name, age, and job title are set. The display() method is called to print the information to the console.

The clone() method is then called on this Employee object to create a copy of it (e2). The display() method is called on the e2 object to print its information to the console. Then, the role of the deg instance variable of e2 is changed to "HR". Finally, the display() method is called on e1 to show that it has not been affected by the change made to e2.

Source Code

//Shallow Copy Object Cloning in Java
/*
class Designation
{
    String role;
    @Override
    public String toString() {
        return role;
    }
}
class Employee implements Cloneable
{
    String name;
    int age;
    Designation deg=new Designation();
 
    public void display()
    {
        System.out.println("Name       : "+name);
        System.out.println("Age        : "+age);
        System.out.println("Department : "+deg);
        System.out.println("----------------------");
    }
    public Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
 
 
}
public class objectCloningDemo {
    public static void main(String[] args) throws CloneNotSupportedException {
 
        Employee e1 =new Employee();
        e1.name="Ram Kumar";
        e1.age=25;
        e1.deg.role="Manager";
        System.out.println("Before Changing Role : ");
        e1.display();
 
        System.out.println("Cloning and Printing E2 object : ");
        Employee e2 = (Employee)e1.clone();
        e2.deg.role="HR";
        e2.display();
 
        System.out.println("After Changing Role : ");
        e1.display();
 
    }
}
*/

Output

Before Changing Role :
Name       : Ram Kumar
Age        : 25
Department : Manager
----------------------
Cloning and Printing E2 object :
Name       : Ram Kumar
Age        : 25
Department : HR
----------------------
After Changing Role :
Name       : Ram Kumar
Age        : 25
Department : HR
----------------------
To download raw file Click Here

Basic Programs