java getter setter_为什么要提供getter 和setter方法?

属性封装在面向对象编程中扮演着重要角色,它允许对获取和设置属性的行为进行控制,如添加验证、隐藏内部表示、隔离接口变化、控制生命周期、提供调试点等。此外,封装还提高了与其他库的互操作性,允许子类覆盖以改变行为,并能作为lambda表达式传递。不同的访问级别使getter和setter能独立控制访问权限。
摘要由CSDN通过智能技术生成

Encapsulation of behavior associated with getting or setting the

property - this allows additional functionality (like validation) to

be added more easily later.

对与get&set类属性有关的类的行为进行封装可以方便以后增加其他功能(比如验证)

Hiding the internal representation of the property while exposing a

property using an alternative representation.

用不同于内部的展现方式对外公布属性

Insulating your public interface from change - allowing the public

interface to remain constant while the implementation changes without

affecting existing consumers.

避免对外接口发生变化 —— 当实现发生变化时,对外接口不变,不会影响到现有的调用方

Controlling the lifetime and memory management (disposal) semantics

of the property - particularly important in non-managed memory

environments (like C++ or Objective-C).

控制属性的生命周期和内存管理 —— 在无内存管理的环境中尤其重要(比如C++和Objective-C)

Providing a debugging interception point for when a property changes

at runtime - debugging when and where a property changed to a

particular value can be quite difficult without this in some

languages.

当属性的值在运行时发生变化的时候,提供一个调试入口 —— 在某些语言中调试属性值的变化是很困难的

Improved interoperability with libraries that are designed to operate

against property getter/setters - Mocking, Serialization, and WPF

come to mind.

提高与那些操作属性的getter/setter的库的互通性 —— 比如Mocking(单测常用的东西,我平时也直接说Mock,不知道怎么翻译), 序列化, WPF等等

Allowing inheritors to change the semantics of how the property

behaves and is exposed by overriding the getter/setter methods.

允许子类继承并覆写修改属性的行为的语义

Allowing the getter/setter to be passed around as lambda expressions

rather than values.

允许getter/setter作为lambda表达式而不是值进行传递

Getters and setters can allow different access levels - for example

the get may be public, but the set could be protected.

getter/setter可以有不同的可访问性,比如get可以public而set则是protected

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值