为什么getter和setter方法在java中很重要? [英] Why are getter and setter method important in java?

查看:98
本文介绍了为什么getter和setter方法在java中很重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被教导要经常使用吸气剂和制定者。但是,我不知道这些方法的优缺点,因为通过实现它们,我们暴露数据并隐藏它。

I have been taught to always use getters and setters. However, I don't know the pros and cons of these methods, as by implementing them we are exposing the data and also hiding it.

我对此感到有些困惑。任何人都可以就我们使用getter / setter的原因以及它们的优势提供一些正确的建议吗?

I am a little confused about this. Can anybody give some proper advice on why we use a getter/setter and what the advantages are?

推荐答案

基本的私人领域使用公共getter和setter除了返回或设置字段之外什么都不做模式在封装时确实完全没有意义,除了它让你有机会在不改变API的情况下更改它。

The basic "private field with public getter and setter that do nothing but return or set the field" pattern is indeed completely pointless when it comes to encapsulation, except that it gives you a chance to change it later without changing the API.

所以不要不假思索地使用那种模式。仔细考虑一下你真正需要的操作。

So don't use that pattern unthinkingly. Carefully consider what operations you actually need.

getter和setter的真正意义在于你应该只在合适的地方使用它们,并且他们可以做的不仅仅是获取和设置字段。

The real point of getters and setters is that you should only use them where they are appropriate, and that they can do more than just get and set fields.


  • 您只能拥有一个getter。然后该物业是只读的。这实际上应该是最常见的情况。

  • 你可以只有一个setter,使该属性可配置,但没有其他任何东西应该依赖于它的值

  • getter可以从多个字段计算一个值而不是返回一个字段。

  • 一个getter可以制作一个防御性副本

  • 一个getter can懒惰地执行昂贵的提取操作并使用字段来缓存值

  • setter可以进行健全性检查并抛出 IllegalArgumentException

  • setter可以通知侦听器值的更改

  • 您可以拥有一个将多个字段设置在一起的setter,因为它们在概念上属于一起。这不符合JavaBeans规范,因此如果依赖于期望JavaBeans的框架或工具,请不要这样做。否则,它是一个有用的选项。

  • You can have only a getter. Then the property is read only. This should actually be the most common case.
  • You can have only a setter, making the property configurable, but communicating that nothing else should depend on its value
  • A getter can compute a value from several fields rather than return one field.
  • A getter can make a defensive copy
  • A getter can perform an expensive fetch operation lazily and use a field to cache the value
  • A setter can do sanity checks and throw IllegalArgumentException
  • A setter can notify listeners of changes to the value
  • You can have a setter that sets multiple fields together because they belong together conceptually. This doesn't adhere to the JavaBeans specification, so don't do it if you depend on frameworks or tools that expect JavaBeans. Otherwise, it's a useful option.

所有这些都是隐藏在简单的getter和setter界面背后的实现细节。这就是封装的内容。

All of these things are implementation details that are hidden behind the simple "getter and setter" interface. That's what encapsulation is about.

这篇关于为什么getter和setter方法在java中很重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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