亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么要提供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 關注
  • 640 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號