17.object Cloning in Java
17.object Cloning in Java
2.Override the clone() Method: You need to override the protected clone()
method from the Object class in your class. This method needs to call
super.clone() to create a shallow copy of the object.
// Getter methods
public String getMake() {
return make;
}
} catch (CloneNotSupportedException e) {
System.out.println("Cloning not supported");
}
}
}
Shallow Object Cloning:
Definition: Shallow cloning creates a new object and copies all fields of the
original object to the new object. However, if the fields themselves are reference
types (objects), only the references to those objects are copied, not the objects
themselves. This means that the new object shares references to the same
objects as the original object.
Behavior: Changes made to mutable objects within the original object will affect
the cloned object since they are referring to the same objects in memory.
class Person implements Cloneable {
private String name;
private Address address;
public Person(String name, Address address) {
this.name = name;
this.address = address;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}}
class Address {
private String city;
public Address(String city) {
this.city = city;
}}
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Address address = new Address("New York");
Person originalPerson = new Person("John", address);
Person clonedPerson = (Person) originalPerson.clone();
// Change city in original object
originalPerson.getAddress().setCity("Los Angeles");
System.out.println("Cloned Person's City: " + clonedPerson.getAddress().getCity()); // Output: Los Angeles
}}
Deep Object Cloning:
Definition: Deep cloning creates a new object and recursively copies all
fields of the original object to the new object, including any objects
referenced by the fields. This ensures that the new object has its own
separate copies of all referenced objects.