简体   繁体   English

如何使用可变成员变量创建不可变类?

[英]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?假设我有一个 Customer 类,它有一个 Address Class 的引用,我们可以通过使成员变量私有 final blah blah 来创建 Customer 类的对象。客户类,现在我们如何使客户类不可变? 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?现在在场景中我们如何使 Customer 类的对象不可变? 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方法中,我们应该返回一个新的地址对象,其属性类似于客户类中的地址引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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