Can create the getter and setter method private? - Stack ...

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

2) The reason that you can do it is because the Java Language Specification says ... The class properties must be accessible using get, set, ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Cancreatethegetterandsettermethodprivate? AskQuestion Asked 10years,7monthsago Modified 10years,7monthsago Viewed 6ktimes -6 0 Cancreatethesetterandgettermethodprivate?Ifyesornowhy? java Share Follow askedAug22,2011at5:39 BoomirajPBoomirajP 22922goldbadges77silverbadges1414bronzebadges 3 Youareaskingwhethergetterandsettercanbemadeprivateoryouwanttoknowthepros-andconsofmakinggetterandsettersasprivatemethods? – Swagatika Aug22,2011at5:41 Onlyaskingcancreatethegetterandsetterprivate? – BoomirajP Aug22,2011at5:43 Yes,youcan.Thereisnorestrictiononthat. – Swagatika Aug22,2011at5:44 Addacomment  |  5Answers 5 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 1 Generallymakingsettersasprivatemethodsisoneofthemanywaysofmakingimmutableobjects. Share Follow answeredAug22,2011at5:43 SwagatikaSwagatika 3,30666goldbadges2929silverbadges3838bronzebadges 5 1 Whyevenmakeasetterthen,whenanycodethatcancallthesettercandirectlymodifytheprivatevariableaswell,andoverrideanysortofchecksthesettermightmake. – Paul Aug22,2011at5:48 Youwillprobablyloosethechecksthesetters/gettersmightdo,modifyingthestatevariabledirectly.Privatesetter/getteristhoughtfulsolutiononlyforthesekindsofadditionalchecks. – panzerschreck Aug22,2011at6:10 IfIwantedtomakeanobjectimmutable,Iwould(amongotherthings)makeitspropertiesfinal.Thenitcouldnothaveasettermethod. – emory Aug22,2011at7:10 @Enomy:Yeahthat'sanotherstrategyofmakingimmutableobjectsbycreatingfinalandprivatefields. – Swagatika Aug22,2011at8:19 Declaringallsettersprivateisnotsufficienttomakeanobjectimmutable.Ifyouhaveanysetters(publicorprivate)youalsoneedsomeschemetopreventthesetterfromchangingtheobjectstateaftertheobjectbecomesimmutable. – StephenC Jan16,2013at9:50 Addacomment  |  1 Cancreatethesetterandgettermethodprivate?Ifyesornowhy? 1)Yesyoucandoit. 2)ThereasonthatyoucandoitisbecausetheJavaLanguageSpecificationsaysyoucan.AsfarastheJLSisconcerned,thereisnothinglinguisticallydifferentbetweengetterandsettermethodsandanyothermethods.Andanymethodcanbedeclaredasprivate. Yourunstatedquestioniswhyyouwoulddoit.Andthereasonissimple:tohidethemethodsfromuseoutsideoftheclass.Andwhymightyoudothat?Here'satypicaluse-case: Wewanttocombinesomelogic(inthiscaseenforcingofaconstraint)withthesetting(orgetting)ofanattribute,butwedon'twantthesetter(orgetter)tobevisible: publicclassFoo{ privateFooparent;//thismustnotchangeonceithasbeenset .... privatevoidsetParent(Fooparent){ if(this.parent!=null){ thrownewSomeException(...); } this.parent; } } Share Follow answeredAug22,2011at7:03 StephenCStephenC 664k9191goldbadges762762silverbadges11481148bronzebadges Addacomment  |  0 Youcandoit,butthereishardlyapoint.Ifthosemethodsareprivatethenanycodethatcancallthosemethodscanalsoaccesstheobjectspropertiesdirectly. Share Follow answeredAug22,2011at5:41 PaulPaul 135k2525goldbadges266266silverbadges256256bronzebadges 2 Iassumethatanycodethatcancallthosemethodsisundermycontrol.IchoosehowtoaccestheobjectspropertiesandIcanchoosetowriteasetter/getterconveniencemethodtosavemyselfthetroubleofrepeatingthesamecodeoverandoveragain. – emory Aug22,2011at7:06 Ihavecreatedacounterexample-stackoverflow.com/questions/7143564/…-wheresomecodethatcouldaccessthesetter/gettermethodscouldnotaccesstheobjectspropertiesdirectly.Admittedly,itstillseemspointless. – emory Aug22,2011at7:08 Addacomment  |  0 Yes,gettersandsetterscanbemadeprivate.IfyouwanttocreateaJavaBean,thenaprivategetter/setterfailstheJavaBeanscriteria,whichstates: Theclasspropertiesmustbeaccessibleusingget,set,is(usedfor booleanpropertiesinsteadofget)andothermethods(so-called accessormethodsandmutatormethods),followingastandard naming-convention.Thisallowseasyautomatedinspectionandupdating ofbeanstatewithinframeworks,manyofwhichincludecustomeditors forvarioustypesofproperties. Share Follow answeredAug22,2011at5:49 BuhakeSindiBuhakeSindi 85.1k2727goldbadges164164silverbadges223223bronzebadges Addacomment  |  0 Thereisnoreasonwhyyoucannotmakegettersandsettersprivate. Whywouldyoudothis?Ifthesettermethodmodifiedapropertyindirectly.Forexample,ifyourcircleclasshadaradiusproperty,thenyoucouldhavesetRadius,setDiameter,setCircumference,setAreamethodsandyoucouldchoosetomakethesemethodsprivate. Infact,ifyouinsertsomeconvolutedcode,youcanhavecodethatcancallthesesetter/gettermethodsthatcannotmodifythepropertiesdirectly(withoutusingreflection).Butitissufficientlyconvolutedthatitseemshardlyworththetrouble. /** *Thisconvolutedclasswillnotworkcorrectlyunlesstheline"this.xRef.set(x)"isline10andtheline"x=this.xRef.get();"isline23 **/ classPrivate { privatevoidsetX(intx) { try { this.xRef.set(x); } catch(IllegalAccessExceptioncause) { assertfalse; } } privateintgetX() { intx; try { x=this.xRef.get(); } catch(IllegalAccessExceptioncause) { x=0; assertfalse; } returnx; } privatefinalReferencexRef=newReference() { @Override publicIntegerget()throwsIllegalAccessException { checkMethod("Private","getX",23); returnsuper.get(); } @Override publicvoidset(Integerval)throwsIllegalAccessException { checkMethod("Private","setX",10); super.set(val); } }; publicstaticvoidmain(String[]args) { Privatep=newPrivate(); p.setX(5); System.out.println(p.getX()); try { p.xRef.set(100); } catch(IllegalAccessExceptioncause) { cause.printStackTrace(); } System.out.println(p.getX()); } } classReference { privateTval; publicvoidset(Tval)throwsIllegalAccessException { this.val=val; } publicTget()throwsIllegalAccessException { returnthis.val; } publicvoidcheckMethod(StringclassName,StringmethodName,intlineNumber)throwsIllegalAccessException { IllegalAccessExceptioncause=newIllegalAccessException(); booleandelta=true; for(StackTraceElemente:cause.getStackTrace()) { if((e.getClassName().equals(className))&&(e.getMethodName().equals(methodName))&&(e.getLineNumber()==lineNumber)) { delta=false; break; } } if(delta) { throwcause; } } } Share Follow answeredAug22,2011at7:02 emoryemory 10.5k22goldbadges2828silverbadges5656bronzebadges Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedjavaoraskyourownquestion. TheOverflowBlog AIandnanotechnologyareworkingtogethertosolvereal-worldproblems GettingthroughaSOC2auditwithyournervesintact FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia NewUserExperience:DeepDiveintoourResearchontheStagingGround–How... AskWizardforNewUsersFeatureTestisnowLive Related 3036 HowdoItestaclassthathasprivatemethods,fieldsorinnerclasses? 4122 WhatarethedifferencesbetweenaHashMapandaHashtableinJava? 3471 Whatisthedifferencebetweenpublic,protected,package-privateandprivateinJava? 3271 WhatisaserialVersionUIDandwhyshouldIuseit? 2717 HowcanIcreateanexecutableJARwithdependenciesusingMaven? 3559 HowcanIcreateamemoryleakinJava? 7320 Whyissubtractingthesetwotimes(in1927)givingastrangeresult? 3695 Whyischar[]preferredoverStringforpasswords? 26280 Whyisprocessingasortedarrayfasterthanprocessinganunsortedarray? 3877 ProperusecasesforAndroidUserManager.isUserAGoat()? HotNetworkQuestions WordpressRedirect301registerpage Whatdoesthisportionofthescoremeanwherethetrebleandbassclefsintersect? Isitimpolitetosendtheprofessorapre-writtenletterofrecommendationforapproval? Constructiveproofofstrongnormalizationforsimplytypedlambdacalculus IsitoktohaveaPCBtrackcrossanotheronadifferentlayer? CanIsubmitmytaxesinmultipleenvelopes? WhatwouldUkrainegainbydisclosingintelligenceinformationaboutPutinassassinationplans? HowcanIfindhotelsinagivenareathatrentunitswithaseparatebedroom? "wecouldtiptheecologyoffinawaythatwouldbereallyunfortunate" Woulditbepossibleforoneairlinertotowanother? Howtomakeatranslucentmaterialthatlookslikethisaxolotltail? Creatingalistofconditions WheredidthethirdsyllableoftheletterWinWD-40go? IsitappropriatetocoldcallaprospectivepostdocPI? GeometryNodes:Howtomaketubefromcurve HowcanIfacilitateafasterpaceofplay? ConvertDateformattoinsertintoMySQLdatabase Meaningof"orwehaveheadphonesorwedon't,so..." Cleverefandcaption-basedcommand-wrongreferences HowchangeinKEissameineveryinertialreferenceframe? Derivingtheapparentangularspeedofastar WhydoesAgustínsay"miércoles"intheEncantomovie?Whatdoesitmean? ConnectingHundredsofServersviaLocalNetwork(LAN)? ITstaffsaidthatLinuxcannotconnecttotheschool'sInternet(EduStar)andrefusedtotry morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-java Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?