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 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
延伸文章資訊
- 1Getters and Setters in Java Explained - freeCodeCamp
Getters and setters are used to protect your data, particularly when creating classes. For each i...
- 2Getter and Setter in Java - GeeksforGeeks
Getter and Setter in Java ... Getter and Setter are methods used to protect your data and make yo...
- 3Significance of Getters and Setters in Java | Baeldung
Getters and Setters play an important role in retrieving and updating the value of a variable out...
- 4Getter、Setter的用與不用
在Java界,有個該不該使用Getter、Setter的老問題,不單是初學者經常覺得多此一舉,就連老手們偶而也會從封裝、維護、抽象化等角度,戰上數回。
- 5[Java] 關於getter與setter | 羅倫斯的IT航海日誌 - - 點部落
[Java] 關於getter與setter ... 在學習物件導向程式語言的時候,每個人一定都有寫到getter與setter的經驗。 ... 這樣的設計目的是為了避免private vari...