猿问

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

一个类提供这两个方法,通常都是public的,意味着任何地方都可以new一个对象然后通过setter修改他们的成员变量,那这个成员变量修饰为private有用什么作用?何不直接就实例.属性修改?
江户川乱折腾
浏览 651回答 2
2回答

qq_花开花谢_0

由于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
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答