java - how Immutable class is created having mutable object as refernce -


i asking basis question 'how make immutable object in java'.

so have 1 address class third party not inherit cloneable interface , mutable class. looks 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 have immutable class called person implements cloneable interface , override clone method.class looks

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 question is, surely can clone person class object how can address class instance cloned. read article shallow cloning , deep cloning. not understand how deep cloning can done thirty party api. or correct me if understood wrong cloning.

i think understand well: clone bad mechanism , there's complete list of things wrong (check out effective java). particularly relevant case, cannot deep-clone object final fields.

instead choose custom mechanism copying objects, such copy-constructors or dedicated methods.

there trick in-memory serialize-deserialize cycle, wouldn't recommend unless performance , efficiency not high on list.


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -