问题描述
在创建不可变类时,所有字段都被声明为final,以便它们的值不能被修改。这没关系,但为什么我们也将它们声明为私有
while creating immutable class all the fields are declared as final so that their value cant be modified.this is okay but why we also declared them as private
推荐答案
如果该字段是对可变对象的引用,则使其 final
将阻止引用反弹一个不同的对象。但是,仍然可以修改对象,实际上是包含对象的侧步不变性。
If the field is a reference to a mutable object, making it final
will prevent the reference from being rebound to a different object. However, the object can still be modified, in effect side-stepping immutability of the containing object.
为了防止这种情况,你可以使字段私人
(如果他们看不到,他们就无法修改它。)
To prevent this, you can make the field private
(if they can't see it, they can't modify it).
例如:
public class Order {
public final List<OrderLine> order_lines = ...;
}
在这里,任何人都可以通过添加/删除/修改来进入并修改订单订单行,即使 order_lines
是 final
。
Here, anyone can come in and modify the order by adding/removing/modifying order lines, even though order_lines
is final
.
这篇关于为什么在创建不可变类时,字段被声明为私有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!