Significance of Getters and Setters in Java | Baeldung

文章推薦指數: 80 %
投票人數:10人

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



請為這篇文章評分?