为什么要在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,
- 不提供任何设定者
- 将所有字段标记为私人
- 制作class final
为什么需要第3步?为什么我要将班级标记为
?
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
的行为,以读取在我的子类中声明的新的可变字段。因此,您的类最初看起来是不可变的,实际上并不是一成不变的。我可以传递这个 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屋!