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
延伸文章資訊
- 1Getter、Setter的用與不用
在Java界,有個該不該使用Getter、Setter的老問題,不單是初學者經常覺得多此一舉,就連老手們偶而也會從封裝、維護、抽象化等角度,戰上數回。
- 2Java Getter and Setter Tutorial - from Basics to Best Practices
In Java, getter and setter are two conventional methods that are used for retrieving and updating...
- 3Getters and Setters in Java Explained - freeCodeCamp
Getters and setters are used to protect your data, particularly when creating classes. For each i...
- 4Significance of Getters and Setters in Java | Baeldung
Getters and Setters play an important role in retrieving and updating the value of a variable out...
- 5Java Getter和Setter:基礎、常見錯誤和最佳實踐 - 每日頭條
Getter和setter在Java中廣泛使用。它看起來很簡單,但是並不是每個程式設計師都能正確地理解和實現這種方法。因此,在本文中,我將深入討論Java中 ...