为什么在创建不可变类时将字段声明为私有? [英] Why, while creating an immutable class, are fields declared as private?

查看:101
本文介绍了为什么在创建不可变类时将字段声明为私有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在创建一个不可变的类时,所有字段都被声明为final,因此它们的值不能被修改.可以,但是为什么我们还要将它们声明为私有?

While creating an immutable class, all the fields are declared as final so that their value can’t be modified. This is okay, but why do we also declare 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.

为防止这种情况,您可以将字段设置为private(如果他们看不到,则无法对其进行修改).

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_linesfinal,任何人都可以通过添加/删除/修改订单行来修改订单.

Here, anyone can come in and modify the order by adding/removing/modifying order lines, even though order_lines is final.

这篇关于为什么在创建不可变类时将字段声明为私有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆