Getters and Setters in Java Explained - freeCodeCamp
文章推薦指數: 80 %
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 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 ADVERTISEMENT
延伸文章資訊
- 1@Getter and @Setter - Project Lombok
You can also put a @Getter and/or @Setter annotation on a class. In that case, it's as if you ann...
- 2Getters and Setters in Java Explained - freeCodeCamp
Getters and setters are used to protect your data, particularly when creating classes. For each i...
- 3Java Encapsulation and Getters and Setters - W3Schools
- 4建立getter 和setter - IBM
建立getter 和setter. 這個對話框可選取要建立的getter 和setter 方法。 您可從程式檔功能表或選定欄位或類型的快速功能表中使用產生Getter 和Setter,或是類型中...
- 5属性的getter 和setter - 现代JavaScript 教程
访问器属性由“getter” 和“setter” 方法表示。在对象字面量中,它们用 get 和 set 表示:. let obj = { get propName() { // 当读取obj.