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
延伸文章資訊
- 1Significance of Getters and Setters in Java | Baeldung
Getters and Setters play an important role in retrieving and updating the value of a variable out...
- 2Getter、Setter的用與不用
在Java界,有個該不該使用Getter、Setter的老問題,不單是初學者經常覺得多此一舉,就連老手們偶而也會從封裝、維護、抽象化等角度,戰上數回。
- 3Java Getter和Setter:基礎、常見錯誤和最佳實踐 - 每日頭條
Getter和setter在Java中廣泛使用。它看起來很簡單,但是並不是每個程式設計師都能正確地理解和實現這種方法。因此,在本文中,我將深入討論Java中 ...
- 4Getters and Setters in Java Explained - freeCodeCamp
Getters and setters are used to protect your data, particularly when creating classes. For each i...
- 5Java 入門指南- getter 與setter - 程式語言教學誌
Java 入門指南- getter 與setter. 屬性(field) 需要有效的封裝(encapsulation) 到物件(object) 裡頭,因此類別(class) 定義屬性時,應該宣告...