Deep cloning of object in java


Now for deep cloning.Please complete shallow cloning before start deep cloning.Deep cloning clones reference object also.
Please take a look Shallow cloning For our tutorial we need to modify some portion of cde in Role and User entity
In role class we add clone method in Role Table And We need to implement Cloneable interface from Role class. and the override clone method
public class Role implements Cloneable
  @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

and then we need to modify User Object's clone method like this.
    @Override
    protected Object clone() throws CloneNotSupportedException {
        User user = (User) super.clone();
        user.setRole((Role)user.getRole().clone());
        return user;
    }

Then you need to run program you can get output like this
This is shallow Cloning Test ::
Main User Admin
Name Users :: Manager
false
Reference of User: User@14318bb
Reference of Cloned User: User@ca0b6
true
Now you can see that change in clone object can not effect original object Thanks...Happy coding...:P
reference:dzone
Reactions

Post a Comment

0 Comments