Getters and Setters in Java Explained - freeCodeCamp

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

Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns ... Search Submityoursearchquery Forum Donate Learntocode—free3,000-hourcurriculum Gettersandsettersareusedtoprotectyourdata,particularlywhencreatingclasses.Foreachinstancevariable,agettermethodreturnsitsvaluewhileasettermethodsetsorupdatesitsvalue.Giventhis,gettersandsettersarealsoknownasaccessorsandmutators,respectively.Byconvention,gettersstartwiththeword"get"andsetterswiththeword"set",followedbyavariablename.Inbothcasesthefirstletterofthevariable'snameiscapitalized:publicclassVehicle{ privateStringcolor; //Getter publicStringgetColor(){ returncolor; } //Setter publicvoidsetColor(Stringc){ this.color=c; } }Thegettermethodreturnsthevalueoftheattribute.Thesettermethodtakesaparameterandassignsittotheattribute.Oncethegetterandsetterhavebeendefined,weuseitinourmain:publicstaticvoidmain(String[]args){ Vehiclev1=newVehicle(); v1.setColor("Red"); System.out.println(v1.getColor()); } //Outputs"Red"Gettersandsettersallowcontroloverthevalues.Youmayvalidatethegivenvalueinthesetterbeforeactuallysettingthevalue.Whyusegettersandsetters?Gettersandsettersallowyoutocontrolhowimportantvariablesareaccessedandupdatedinyourcode.Forexample,considerthissettermethod:publicvoidsetNumber(intnumber){ if(number<1||number>10){ thrownewIllegalArgumentException(); } this.number=num; }ByusingthesetNumbermethod,youcanbesurethevalueofnumberisalwaysbetween1and10.Thisismuchbetterthanupdatingthenumbervariabledirectly:obj.number=13;Ifyouupdatenumberdirectly,it'spossiblethatyou'llcauseunintendedsideeffectssomewhereelseinyourcode.Here,settingnumberto13violatesthe1to10constraintwewanttoestablish.MakingnumberaprivatevariableandusingthesetNumbermethodwouldpreventthisfromhappening.Ontheotherhand,theonlywaytoreadthevalueofnumberisbyusingagettermethod:publicintgetNumber(){ returnthis.number; } Ifthisarticlewashelpful,tweetit. Learntocodeforfree.freeCodeCamp'sopensourcecurriculumhashelpedmorethan40,000peoplegetjobsasdevelopers.Getstarted



請為這篇文章評分?