Significance of Getters and Setters in Java | Baeldung
文章推薦指數: 80 %
Getters and Setters play an important role in retrieving and updating the value of a variable outside the encapsulating class. StartHereCourses ▼▲ RESTwithSpring(30%off) ThecanonicalreferenceforbuildingaproductiongradeAPIwithSpring LearnSpringSecurity(30%off) ▼▲ THEuniqueSpringSecurityeducationifyou’reworkingwithJavatoday LearnSpringSecurityCore(30%off) FocusontheCoreofSpringSecurity5 LearnSpringSecurityOAuth(30%off) FocusonthenewOAuth2stackinSpringSecurity5 LearnSpring(30%off) Fromnoexperiencetoactuallybuildingstuff LearnSpringDataJPA(30%off) ThefullguidetopersistencewithSpringDataJPA Guides ▼▲ Persistence ThePersistencewithSpringguides REST TheguidesonbuildingRESTAPIswithSpring Security TheSpringSecurityguides About ▼▲ FullArchive Thehighleveloverviewofallthearticlesonthesite. BaeldungEbooks DiscoverallofoureBooks AboutBaeldung AboutBaeldung. MarchDiscountLaunch2022 We’refinallyrunningaspringlaunch.AllCoursesare30%offuntilnextFriday: >>GETACCESSNOW 1.Introduction GettersandSettersplayanimportantroleinretrievingandupdatingthevalueofavariableoutsidetheencapsulatingclass.Asetterupdatesthevalueofavariable,whileagetterreadsthevalueofavariable. Inthistutorial,we'lldiscusstheproblemsofnotusinggetters/setters,theirsignificance,andcommonmistakestoavoidwhileimplementingtheminJava. 2.LifeWithoutGettersandSettersinJava Thinkaboutasituationwhenwewanttochangethestateofanobjectbasedonsomecondition.Howcouldweachievethatwithoutasettermethod? Markingthevariableaspublic,protected,ordefault Changingthevalueusingadot(.)operator Let'slookattheconsequencesofdoingthis. 3.AccessingVariablesWithoutGettersandSetters First,foraccessingthevariablesoutsideaclasswithoutgetters/setters,wehavetomarkthoseaspublic,protected,ordefault.Thus,we'relosingcontroloverthedataandcompromisingthefundamentalOOPprinciple–encapsulation. Second,sinceanyonecanchangethenon-privatefieldsfromoutsidetheclassdirectly,wecannotachieveimmutability. Third,wecannotprovideanyconditionallogictothechangeofthevariable.Let'sconsiderwehaveaclassEmployeewithafieldretirementAge: publicclassEmployee{ publicStringname; publicintretirementAge; //Constructor,butnogetter/setter } Notethat,herewe'vesetthefieldsaspublictoenableaccessfromoutsidetheclassEmployee.Now,weneedtochangetheretirementAgeofanemployee: publicclassRetirementAgeModifier{ privateEmployeeemployee=newEmployee("John",58); privatevoidmodifyRetirementAge(){ employee.retirementAge=18; } } Here,anyclientoftheEmployeeclasscaneasilydowhattheywantwiththeretirementAgefield.There'snowaytovalidatethechange. Fourth,howcouldweachieveread-onlyorwrite-onlyaccesstothefieldsfromoutsidetheclass? Therecomegettersandsetterstoyourrescue. 4.SignificanceofGettersandSettersinJava Outofmany,let'scoversomeofthemostimportantbenefitsofusinggettersandsetters: Ithelpsusachieveencapsulationwhichisusedtohidethestateofastructureddataobjectinsideaclass,preventingunauthorizeddirectaccesstothem Achieveimmutabilitybydeclaringthefieldsasprivateandusingonlygetters Gettersandsettersalsoallowadditionalfunctionalitieslikevalidation,errorhandlingthatcouldbeaddedmoreeasilyinthefuture.Thuswecanaddconditionallogicandprovidebehavioraccordingtotheneeds Wecanprovidedifferentaccesslevelstothefields;forexample,theget(read-access)maybepublic,whiletheset(write-access)couldbeprotected Controloversettingthevalueofthepropertycorrectly Withgettersandsetters,weachieveonemorekeyprincipleofOOP,i.e.,abstraction,whichishidingimplementationdetailssothatnoonecanusethefieldsdirectlyinotherclassesormodules 5.AvoidingMistakes Belowarethemostcommonmistakestoavoidwhileimplementinggettersandsetters. 5.1.UsingGettersandSettersWithPublicVariables Publicvariablescanbeaccessedoutsidetheclassusingadot(.)operator.Thereisnosenseinusinggettersandsettersforpublicvariables: publicclassEmployee{ publicStringname; publicintretirementAge; publicvoidsetName(Stringname){ this.name=name; } publicStringgetName(){ returnthis.name; } //getter/setterforretirementAge } Inthiscase,anythingthatcanbedonewithgettersandsetterscanalsobedonebymakingthefieldsimplypublic. Asaruleofthumb,weneedto alwaysusethemostrestrictedaccessmodifiersbasedontheneedtoachieveencapsulation. 5.2.AssigningObjectReferencesDirectlyintheSetterMethods Whenweassignobjectreferencedirectlyinthesettermethods,boththesereferencespointtoasingleobjectinmemory.So,changesmadeusinganyofthereferencevariablesareactuallymadeonthesameobject: publicvoidsetEmployee(Employeeemployee){ this.employee=employee; } However,wecancopyalltheelementsfromoneobjecttoanotherobjectusingadeepcopy.Duetothis,thestateofthisobjectbecomesindependentoftheexisting(passed)employeeobject: publicvoidsetEmployee(Employeeemployee){ this.employee.setName(employee.getName()); this.employee.setRetirementAge(employee.getRetirementAge()); } 5.3.ReturningObjectReferencesDirectlyFromtheGetterMethods Similarly,ifthegettermethodreturnsthereferenceoftheobjectdirectly,anyonecanusethisreferencefromtheoutsidecodetochangethestateoftheobject: publicEmployeegetEmployee(){ returnthis.employee; } Let'susethisgetEmployee() methodandchangetheretirementAge: privatevoidmodifyAge(){ EmployeeemployeeTwo=getEmployee(); employeeTwo.setRetirementAge(65); } Thisleadstotheunrecoverablelossoftheoriginalobject. So,insteadofreturningthereferencefromthegettermethod,weshouldreturnacopyoftheobject.Onesuchwayisasbelow: publicEmployeegetEmployee(){ returnnewEmployee(this.employee.getName(),this.employee.getRetirementAge()); } However,weshouldalsokeepinmindthatcreatingcopiesofobjectswithinthegetterorsettermightnotalwaysbeabestpractice.Forexample,callingtheabovegettermethodinaloopcouldresultinanexpensiveoperation. Ontheotherhand,ifwewantthatourcollectionshouldremainunmodifiable,itwouldmakesensetoreturnacopyofthecollectionfromagetter.Wethenhavetodeterminewhichapproachsuitsbestinacertainsituation. 5.4.AddingUnnecessaryGettersandSetters Byhavinggettersandsetters,wecancontroltheaccessandassignmentofthemembervariables.But,inmanyplaces,itturnsouttobeunnecessary.Moreover,itmakesthecodeverbose: privateStringname; publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } Simplydefiningpublicgettersandsettersforaprivatefieldinaclassisequivalenttomakingthefieldpublicwithoutgettersandsetters.So,it'salwaysadvisabletodecidethoughtfullywhethertodefineaccessormethodsforallthefieldsornot. 6.Conclusion Inthistutorial,wediscussedtheprosandconsofusinggettersandsettersinJava.Wealsodiscussedsomecommonmistakestobeavoidedwhileimplementinggettersandsetters,andhowtousethoseappropriately MarchDiscountLaunch2022 We’refinallyrunningaspringlaunch.AllCoursesare30%offuntilnextFriday: >>GETACCESSNOW Genericfooterbanner LearningtobuildyourAPIwithSpring? DownloadtheE-book 6Comments Oldest Newest InlineFeedbacks Viewallcomments ViewComments LoadMoreComments Commentsareclosedonthisarticle! LaunchDiscount30% OnAllCourses VIEWDETAILS Followthe Java Category FollowtheJavacategorytogetregularinfoaboutthenewarticlesandtutorialswepublishhere. FOLLOWTHEJAVACATEGORY wpDiscuzInsert
延伸文章資訊
- 1Getter、Setter的用與不用
在Java界,有個該不該使用Getter、Setter的老問題,不單是初學者經常覺得多此一舉,就連老手們偶而也會從封裝、維護、抽象化等角度,戰上數回。
- 2Java Getter and Setter Tutorial - from Basics to Best Practices
In Java, getter and setter are two conventional methods that are used for retrieving and updating...
- 3Java 入門指南- getter 與setter - 程式語言教學誌
Java 入門指南- getter 與setter. 屬性(field) 需要有效的封裝(encapsulation) 到物件(object) 裡頭,因此類別(class) 定義屬性時,應該宣告...
- 4Java Encapsulation and Getters and Setters - W3Schools
... CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more. ... private = restricted ac...
- 5[Java] 關於getter與setter | 羅倫斯的IT航海日誌 - - 點部落
[Java] 關於getter與setter ... 在學習物件導向程式語言的時候,每個人一定都有寫到getter與setter的經驗。 ... 這樣的設計目的是為了避免private vari...