First of all Java clone() method has given in Object class with below
public class Clones { public static void main(String[] args) throws CloneNotSupportedException { Person p1 = new Person( "AAA" , 123 , 100 , 200 ); System.out.println( "Original" ); System.out.println(p1.salary.basic); Person p2 = (Person) p1.deepClone(); //p2.name = "BBB"; //p2.salary.basic = 2222; System.out.println(p1.equals(p2)); System.out.println( "Clone" ); System.out.println(p2.salary.basic); System.out.println( "Original" ); System.out.println(p1.salary.basic); } } // cloneable class implements Cloneable class Person implements Cloneable { public String name = null ; public int id = 0 ; public Salary salary = null ; public Person(String name, int id, int basicSal, int bonusSal) { this .name = name; this .id = id; // using Object type member to test for cloning Salary sal = new Salary(); sal.basic = basicSal; sal.bonus = bonusSal; this .salary = sal; } // shallow copying protected Object clone() throws CloneNotSupportedException { // This is default cloning provided by the Object.clone() return super .clone(); } // deep copying protected Object deepClone() throws CloneNotSupportedException { // The clone() method produces an Object, which must be recast to the proper type Person p = (Person) super .clone(); // In deep cloning, we also clone the member objects, but for this to work - //member objects should be Cloneable p.salary = (Salary) p.salary.clone(); return p; } } // member object of Person class as Cloneable. If it was not, then deep cloning //would not have been possible class Salary implements Cloneable { public int basic = 0 ; public int bonus = 0 ; public int getSalary() { return basic + bonus; } // implementing clone() protected Salary clone() throws CloneNotSupportedException { Salary s = (Salary) super .clone(); return s; } } // Cloneables with final fields - not meant go together. No error, but when try //to change, it cribs. // The only solution is to remove the final modifier from the field, giving up //the benefits the modifier conferred. |
Blog provide core concept of Java , J2ee , Struts Framework, Spring, Hibernate, apache ofbiz,Hybris e-commerce suit.Net4.0 framework,Websphere Application Server (WAS), DB2, WSAD and JavaScript. Also covers Tips and Tricks , Codes , Tutorials , Solutions for Developers , latest Interview Questions & Answers
Java Clone() concept | how clone work in java | java clone interivew question answer
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.