Shallow Copy Object Cloning in Java


One method of copying an object is the shallow copy. In that case a new object B is created, and the field’s values of A are copied over to B. Default behavior when cloning an object is to perform a shallow copy of the object's fields. In that case, both the original object and the cloned object, hold references to the same objects.

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