Thursday, 22 November 2018

Java clone object – cloning in java


  • Java Object class comes with native clone() method that returns the copy of the existing instance.
  • To use java object clone method, we have to implement the marker interface java.lang.Cloneable so that it won’t throw CloneNotSupportedException at runtime.
  • Also Object clone is a protected method, so we will have to override it to use with other classes
  • Student.java
    • public class Student implements Cloneable { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
  • App.java
    • public class App { public static void main(String[] args) throws CloneNotSupportedException { Student student1 = new Student(); student1.setId(1); student1.setName("Sonu"); Student student2 = (Student) student1.clone(); System.out.println(student2.getName()); if (student1.equals(student2)) { System.out.println("EQUAL"); } } }
  • s1 == s2: false
    • So s1 and s2 are two different object, not referring to same object. This is in agreement of the java clone object requirement.
  • s1.name == s2.name: true
    • So both s1 and s2 object variables refer to same object.
  • Shallow copy
    • Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.
  • Deep copy
    • A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.

No comments:

Post a Comment

Search This Blog

Contact us

Name

Email *

Message *