在不可变类中,为什么字段被标记为私有? [英] In immutable class why fields are marked as private?

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

问题描述

在创建不可变类时将字段设为私有有什么好处?

What is the benefit of making fields private while creating an immutable class?

我见过为什么在创建不可变类时,字段被声明为私有?但我从这篇文章中得不到任何理解。

I have seen why while creating immutable class, fields are declared as private? but I didn't get understand anything from this post.

任何人都可以请解释我一样吗?

Can anybody please explain me the same?

推荐答案

最好的解释方法是举个例子:

The best way to explain is with an example:

  public class Immutable {
     private final char[] state = "Hi Mom".getChars();

     public char[] getState() {
         return state.clone();
     }
  }

这里我们有一个正确封装的,不可变的类。没有什么可以改变状态(模数讨厌的反思技巧)。

Here we have a properly encapsulated, immutable class. Nothing can change the state (modulo nasty reflective tricks).

现在让我们改变对该字段的访问:

Now lets JUST change the access on the field:

  public class Immutable {
     public final char[] state = "Hi Mom".getChars();

     public char[] getState() {
         return state.clone();
     }
  }

注意我们仍然在getState中制作防御性副本。 ..和以前一样...但现在有人可以这样做:

Note we are still making the defensive copy in getState ... as before ... but now someone can do this:

  Immutable mu = new Immutable();
  mu.state[1] = 'o';

...我们所谓的不可变对象的状态已经改变。

... and our supposedly immutable object's state has changed.

这就是为什么保持字段 private 是个好主意的原因之一。 (显然,这仅适用于引用类型。)

That is ONE reason why it is a good idea to keep the fields private. (Obviously, this only applies to reference types.)

第二个原因是封装。将字段声明为私有隐藏实现细节,这可以降低不必要的交叉耦合的风险。如果我不这样做,那么我(或其他程序员)可能会想要编写依赖于 Immutable 的内部的代码。如果我需要改变它,那将导致问题;例如将 state 的类型更改为 String 。 需要更多代码检查/更改的问题。

A SECOND reason is encapsulation. Declaring fields as private hides implementation details, which reduces the risk of unwanted cross-coupling. If I don't do this, then I (or some other programmer) might be tempted to write code that depends on the internals of Immutable. That is going to lead to problems if I need to change them; e.g. changing the type of state to String. Problems as in "lots more code to check / change".

第三个原因是非私人(特别是公共)字段可能是子类化的障碍。如果我将一个字段声明为 public ,那么我就不能在子类中取消声明它。如果我想隐藏字段或修改子类中字段的行为(通过覆盖)......我不能。相比之下,如果字段是私有的并且通过实例方法进行访问,我可以覆盖子类中的那些方法。或者我可以选择不使用该字段。

A THIRD reason is that non-private (and particularly public) fields can be an impediment to subclassing. If I declare a field as public then, the I can't undeclare it in a subclass. If I want to hide the field or modify the behavior of the field in a subclass (by overriding) ... I can't. By contrast, if the field is private and access is via instance methods, I can override those methods in subclasses. Or I can choose to not use the field at all.

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

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