简体   繁体   中英

How to create immutable class with mutable member variable(s)?

Suppose I have a Customer class which have a reference of Address Class, we can make objects of Customer class by making member variable private final blah blah.... my question is this address class is mutable with getters and setters which has its reference in Customer class, now how can we make Customer class immutable? Does making this Address reference in customer class suffice to make it an immutable class(objects of customer class immutable) Could someone explain?

Now in the scenario how do we make objects of Customer class immutable? and how the relationship between Customer and Address is shown in the memory?Can somebody answer this please?

public final class Customer{
    private final String name;
    private final Address address;

    public Customer(String name, Address address){
        this.name=name;
        this.address= address;
    }

    public String getName(){
        return this.name;
    }

    public String getAddress(){
        return this.name;
    }

}

public class Address{
 private String streetName;
 private Long pincode;

 public void setStreeName(String streetName){
    this.streetName = streetName;
}

 public void setPincode(long pincode){
    this.pincode = pincode;
}

public String getStreetName(){
   return this.streeName;
}

public long getPincode(){
   return this.pincode;
}

}

在上面的客户类中,其他数据类型是原始的(不可变的),而地址类不是,所以在地址引用的getter方法中,我们应该返回一个新的地址对象,其属性类似于客户类中的地址引用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM