简体   繁体   中英

Immutable class with mutable member field

Suppose I have an immutable class say Employee with a mutable member address field of type Address class shown below:

public final class Employee{
    private final Integer empId;
    private final String empName;
    private final Address address;

    public Integer getEmpId(){
        return empId;
    }
    public String getEmpName(){
        return empName;
    }
    public Address getAddress(){
        return address;
    }
}

public class Address {
    private String firstLine;
    private String secondLine;
    private Integer pinCode;

    public String getFirstLine() {
        return firstLine;
    }
    public void setFirstLine(String firstLine) {
        this.firstLine = firstLine;
    }
    public String getSecondLine() {
        return secondLine;
    }
    public void setSecondLine(String secondLine) {
        this.secondLine = secondLine;
    }
    public Integer getPinCode() {
        return pinCode;
    }
    public void setPinCode(Integer pinCode) {
        this.pinCode = pinCode;
    }   
}

As seen above the Employee class tries to be immutable but is it really so?

We can change the address of an Employee object breaking the immutability. What are the ways in which the Employee class can still be immutable despite having mutable member?

An absolutely immutable class can only be if:

  1. The class is final
  2. All fields are final
  3. If the field is an object, then inside this object all fields must be immutable as well and the class itself must also be final.

As a consequence, setters should not be present in this classes.

Therefore, in your case, partial immutability is achieved.

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