为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

江户川乱折腾 2019-05-22 16:24:03
一个类提供这两个方法,通常都是public的,意味着任何地方都可以new一个对象然后通过setter修改他们的成员变量,那这个成员变量修饰为private有用什么作用?何不直接就实例.属性修改?
查看完整描述

2 回答

?
qq_花开花谢_0

TA贡献1835条经验 获得超7个赞

由于stackoverflow上已有人提出过这个问题,并且解答也很好,我就直接搬运最高票过来,并稍作翻译。
Encapsulationofbehaviorassociatedwithgettingorsettingtheproperty-thisallowsadditionalfunctionality(likevalidation)tobeaddedmoreeasilylater.
对与get&set类属性有关的类的行为进行封装可以方便以后增加其他功能(比如验证)
Hidingtheinternalrepresentationofthepropertywhileexposingapropertyusinganalternativerepresentation.
用不同于内部的展现方式对外公布属性
Insulatingyourpublicinterfacefromchange-allowingthepublicinterfacetoremainconstantwhiletheimplementationchangeswithoutaffectingexistingconsumers.
避免对外接口发生变化——当实现发生变化时,对外接口不变,不会影响到现有的调用方
Controllingthelifetimeandmemorymanagement(disposal)semanticsoftheproperty-particularlyimportantinnon-managedmemoryenvironments(likeC++orObjective-C).
控制属性的生命周期和内存管理——在无内存管理的环境中尤其重要(比如C++和Objective-C)
Providingadebugginginterceptionpointforwhenapropertychangesatruntime-debuggingwhenandwhereapropertychangedtoaparticularvaluecanbequitedifficultwithoutthisinsomelanguages.
当属性的值在运行时发生变化的时候,提供一个调试入口——在某些语言中调试属性值的变化是很困难的
Improvedinteroperabilitywithlibrariesthataredesignedtooperateagainstpropertygetter/setters-Mocking,Serialization,andWPFcometomind.
提高与那些操作属性的getter/setter的库的互通性——比如Mocking(单测常用的东西,我平时也直接说Mock,不知道怎么翻译),序列化,WPF等等
Allowinginheritorstochangethesemanticsofhowthepropertybehavesandisexposedbyoverridingthegetter/settermethods.
允许子类继承并覆写修改属性的行为的语义
Allowingthegetter/settertobepassedaroundaslambdaexpressionsratherthanvalues.
允许getter/setter作为lambda表达式而不是值进行传递
Gettersandsetterscanallowdifferentaccesslevels-forexamplethegetmaybepublic,butthesetcouldbeprotected.
getter/setter可以有不同的可访问性,比如get可以public而set则是protected
                            
查看完整回答
反对 回复 2019-05-22
  • 2 回答
  • 0 关注
  • 650 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号