为什么要在 Java 中声明一个不可变的类 final? [英] Why would one declare an immutable class final in Java?
问题描述
我读到要在 Java 中使 类不可变,我们应该执行以下操作,
I read that to make a class immutable in Java, we should do the following,
- 不要提供任何 setter
- 将所有字段标记为私有
- 使课程最终化
为什么需要第 3 步?为什么要标记类 final
?
Why is step 3 required? Why should I mark the class final
?
推荐答案
如果您不将类标记为 final
,我可能会突然使您看似不可变的类实际上是可变的.例如,考虑以下代码:
If you don't mark the class final
, it might be possible for me to suddenly make your seemingly immutable class actually mutable. For example, consider this code:
public class Immutable {
private final int value;
public Immutable(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
现在,假设我执行以下操作:
Now, suppose I do the following:
public class Mutable extends Immutable {
private int realValue;
public Mutable(int value) {
super(value);
realValue = value;
}
public int getValue() {
return realValue;
}
public void setValue(int newValue) {
realValue = newValue;
}
public static void main(String[] arg){
Mutable obj = new Mutable(4);
Immutable immObj = (Immutable)obj;
System.out.println(immObj.getValue());
obj.setValue(8);
System.out.println(immObj.getValue());
}
}
请注意,在我的 Mutable
子类中,我覆盖了 getValue
的行为以读取在我的子类中声明的新的可变字段.因此,最初看起来不可变的类实际上并不是不可变的.我可以在任何需要 Immutable
对象的地方传递这个 Mutable
对象,假设对象是真正不可变的,这可能会对代码造成非常糟糕的事情.标记基类 final
可以防止这种情况发生.
Notice that in my Mutable
subclass, I've overridden the behavior of getValue
to read a new, mutable field declared in my subclass. As a result, your class, which initially looks immutable, really isn't immutable. I can pass this Mutable
object wherever an Immutable
object is expected, which could do Very Bad Things to code assuming the object is truly immutable. Marking the base class final
prevents this from happening.
希望这有帮助!
这篇关于为什么要在 Java 中声明一个不可变的类 final?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!