I am asking very basis question about 'How to make immutable Object in java'.
So I have one Address class from third party which does not inherit any Cloneable interface and its mutable class. It looks like this
public class Address {
private String city;
private String address;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Now I have another immutable class called Person which implements Cloneable interface and also override clone method.Class Looks like this
public class Person implements Cloneable {
private String name;
private Address address;
public Person() {
}
public Person(String name, Address address) {
this.name = name;
this.address = address;
//this.address = (Address) address.clone();
}
public String getName() {
return name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Person person = (Person) super.clone();
return super.clone();
}
public Address getAddress() {
return address;
}
@Override
public String toString() {
return "name:" + name + ", address" + address.getAddress() + ", city="
+ address.getCity();
}
}
Now my question is, surely I can clone the Person class object but how can address class instance be cloned. I also read some article about shallow cloning and deep cloning. But I could not understand the how deep cloning can be done with thirty party API. Or correct me if I understood something wrong about cloning.