如何在Java中创建一个可变类

时间:2015-11-07 15:40:36

标签: java class immutability

我刚刚找到了一个教程,该教程描述了如何使类不可变

问题是,tryModification()方法中Integer类型的变量已经是不可变的,你认为这个类代表不变性吗?

import java.util.Date;

public final class ImmutableClass {

private final Integer immutableField1;

private final String immutableField2;

private final Date mutableField;

//default private constructor will ensure no unplanned construction of
//the class
private ImmutableClass(Integer fld1, String fld2, Date date){

    this.immutableField1 = fld1;
    this.immutableField2 = fld2;
    this.mutableField = new Date(date.getTime());




}

//Factor method to store object creation logic in single place
public static ImmutableClass createNewInstance(Integer fld1, String fld2, 
        Date date){

    return new ImmutableClass(fld1, fld2, date);


}

public Integer getImmutableField1(){

    return immutableField1;
}

public String getImmutableField2(){
    return immutableField2;
}

//Date class is mutable so we need little care here
//we should not return the reference of original instance variable
//Instead, a new date object, with content copied to it, should be returned 

public Date getMutableField(){

    return new Date(mutableField.getTime());
}

public String toString(){

    return immutableField1 + " " + immutableField2 + " " + mutableField;



}

}

import java.util.Date;

公共类TestMain {

public static void main(String args[]){





    ImmutableClass im = 
            ImmutableClass.createNewInstance(100, "test", new Date());

    System.out.println(im);

    tryModification(im.getImmutableField1(), im.getImmutableField2(), im.getMutableField());
    System.out.println(im);

    System.out.println(test);



}

private static void tryModification(Integer fld1, String fld2, 
        Date mutableField){

    fld1 = 304;
    fld2 = "Test Changed";
    mutableField.setDate(10);




}

}

1 个答案:

答案 0 :(得分:1)

是的,它是一个不可改变的类。你已经完成了所有正确的事情 - 课程是最终的,所有的领域都是最终的,你已经制作了传递给构造函数的可变对象的副本(Date)和你的{ {1}}方法也返回一个副本。

行之所以

getMutableField

改变您的类的实例是tryModification(im.getImmutableField1(), im.getImmutableField2(), im.getMutableField()); 返回im.getMutableField()Date个实例的副本实例