[英]How to Make a Class Mutable in Java
I just found a tutorial, the tutorial described how to make a class immutable 我刚刚找到了一个教程,该教程描述了如何使一个类不可变
The question is, variable of Integer type in the tryModification() method is already immutable, do you think this class represents immutability? 问题是,tryModification()方法中Integer类型的变量已经不可变,您认为此类表示不可变吗?
import java.util.Date; 导入java.util.Date;
public final class ImmutableClass { 公共最终课程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; 导入java.util.Date;
public class TestMain { 公共类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);
}
} }
Yes, it's an immutable class. 是的,这是一门不变的课。 You've done all the right things - the class is final, all the fields are final, you've made a copy of the mutable object passed to the constructor (the Date
), and your getMutableField
method returns a copy too. 您已经做了所有正确的事情-类是最终的,所有字段都是最终的,已经制作了传递给构造函数的可变对象的副本( Date
),并且getMutableField
方法也返回了副本。
The reason why the line 之所以行
tryModification(im.getImmutableField1(), im.getImmutableField2(), im.getMutableField());
does not mutate the instance of your class is that im.getMutableField()
returns a copy of the Date
instance in the ImmutableClass
instance. 不发生变异的类的实例是im.getMutableField()
返回的副本 Date
在实例ImmutableClass
实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.