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

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

问题描述

我一直被教导要始终使用 getter 和 setter.但是,我不知道这些方法的优缺点,因为通过实施它们,我们暴露了数据并隐藏了它.

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.

  • 你只能有一个吸气剂.然后该属性是只读的.这实际上应该是最常见的情况.
  • 你可以只有一个 setter,使属性可配置,但传达没有其他东西应该依赖于它的值
  • getter 可以从多个字段计算一个值,而不是返回一个字段.
  • getter 可以制作防御性副本
  • getter 可以懒惰地执行昂贵的获取操作并使用字段来缓存值
  • setter 可以进行完整性检查并抛出 IllegalArgumentException
  • setter 可以通知侦听器值的更改
  • 您可以使用一个 setter 将多个字段设置在一起,因为它们在概念上属于一起.这不符合 JavaBeans 规范,因此如果您依赖需要 JavaBeans 的框架或工具,请不要这样做.否则,这是一个有用的选择.

所有这些都是隐藏在简单的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天全站免登陆