How to use constructors in java, android? - Stack Overflow

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

class Foo{ private int x; private String name; Foo(int x){ //constructor 1 this(x, "Default Name"); } Foo(String name){ //constructor 2 ... 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 Howtouseconstructorsinjava,android? AskQuestion Asked 7yearsago Active 2years,9monthsago Viewed 12ktimes 0 0 Ihaveashortquestionaboutthefollowingcodefrom http://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/ HereareusedtwoConstructors,onewiththeid,andtheotherwithout-Idon'tunderstandwhy.What'sthebenefit? Ialreadyreadthisthread: Whydoesthisclasshavetwoconstructors? TheanswerIcouldunderstandis,thatIcancreateaTagwithidandnot,butI'mtryingtounderstand,howtoknowwhichconstructoritshalluse?Isitjustbythenumberofparameters? publicclassTag{ intid; Stringtag_name; //constructors publicTag(){ } publicTag(Stringtag_name){ this.tag_name=tag_name; } publicTag(intid,Stringtag_name){ this.id=id; this.tag_name=tag_name; } //... } javaconstructordefault-constructor Share Improvethisquestion Follow editedMay23'17at10:26 CommunityBot 111silverbadge askedJan8'15at21:03 BobbBobb 7111goldbadge11silverbadge44bronzebadges 6 1 Tagtag=newTag();,parameterlessconstructor;Tagtag=newTag("name");constructorwithstringparameter;Prettyeasyfortheprogrammerandthecompilertoseethedifference – KevinDiTraglia Jan8'15at21:05 1 Yes,onlybytheamountandtypeoftheparameterspassed. – Kon Jan8'15at21:06 1 YestheorderandtypeoftheargumentsmakeupthesignatureoftheconstructorsolikeKevinsaid,newTag()istheonewithoutanyparameters.newTag("string")willbetheonethattakesatag.newTag(123,"string")willcalltheconstructoridnumberandstring..butnewTag("string",123)willgiveyouacompileerrorsincetherearenoconstructorsthatlooklikepublicTag(Stringtag_name,intid). – Rob Jan8'15at21:09 Allanswersarealreadyprovided.However,thedefaultconstructor(theonethatdoesnotacceptanyparameters)isnotreallynecessarytobeimplemented,asitwillbedefinedbythecompilerwhenleftoutoftheimplementation.Tryingtodecidewhichonetouseisjustbylookingatthesignature(thusparams)provided. – RvdV79 Jan8'15at21:20 @RvdV79Nottrue.Thecompileronlysynthesizesadefaultparameterwhentheuserdoesnotdefineonethemselves. – ThornG Jan8'15at21:24  |  Show1morecomment 3Answers 3 Active Oldest Votes 5 Yes,onlybyitsamountofparameters. It'scalled"overloading"offunctions.Youcanoverloadafunctionbyprovidingthesamesignaturewithdifferentparameters(accordingtotheirtypeandorder). TheJVMwillthendecidewhichmethodtouseinacertainsituation. Pleasenote: IfyouprovideaconstructortheJVMwon'tprovideadefaultconstructoranymore. classFoo{ privateintx; privateStringname; Foo(intx){//constructor1 this(x,"DefaultName"); } Foo(Stringname){//constructor2 this(0,name); } Foo(intx,Stringname){//constructor3 this.x=x; this.name=name; } } Foof1=newFoo(9);//callsconstructor1,whowillcallconstructor3 //f1.x=9,f1.name="DefaultName" Foof2=newFoo("Test");//callsconstructor2,whowillcallconstructor3 //f2.x=0;f2.name="Test" Foof3=newFoo(3,"John");//callsconstructor3 //f3.x=3;f3.name="John" Foof4=newFoo()//Thiswon'twork!NodefaultConstructorprovided! Share Improvethisanswer Follow editedMar26'19at21:43 answeredJan8'15at21:25 TimHallyburtonTimHallyburton 2,39111goldbadge1717silverbadges2929bronzebadges Addacomment  |  0 **whichconstructoritshalluse?onlyofitsamountofparemeters? ** Yes,forexampleIfyoucall TagnewTag=newTag(); itwillcall publicTag(){ } butifyoucall TagnewTag=newTag("Name"); itwillcall publicTag(Stringtag_name){ } andsoon byhowmanyargumentsyoupasstotheconstructorthatwayitwillknowwhichonetocall Share Improvethisanswer Follow answeredJan8'15at21:18 AbdiAbdi 1,08288silverbadges1010bronzebadges Addacomment  |  0 Thecompilerknows"whichconstructoritshalluse"byarule,intheJavaLanguageSpecification. Aresume: Isbysignatureofthemethod(thetypeandorderofarguments---theexceptionsdonteffectthesignature,andthereturntypetoo).Thisisnotrestrictedonlybytheconstructor,butanymethod,properlyOverloaded;Youcanstudythesebytopicof"Overloading".ThereasontoOverloadamethod---oraconstructortoo---,istogivemoreflexibility. Share Improvethisanswer Follow answeredJan8'15at21:31 GBisconciniGBisconcini 71422goldbadges66silverbadges2424bronzebadges 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?Browseotherquestionstaggedjavaconstructordefault-constructororaskyourownquestion. TheOverflowBlog Planfortradeoffs:Youcan’toptimizeallsoftwarequalityattributes AchatwiththefolkswholeadtrainingandcertificationatAWS FeaturedonMeta We’vemadechangestoourTermsofService&PrivacyPolicy-January2022 Newpostsummarydesignsongreatesthitsnow,everywhereelseeventually 2021:ayearinmoderation SunsettingJobs&DeveloperStory Visitchat Linked 5 Whydoesthisclasshavetwoconstructors? Related 7315 IsJava"pass-by-reference"or"pass-by-value"? 3701 HowdoIefficientlyiterateovereachentryinaJavaMap? 4268 AvoidingNullPointerExceptioninJava 2499 HowdoIcalloneconstructorfromanotherinJava? 4465 HowdoIread/convertanInputStreamintoaStringinJava? 3416 WhentouseLinkedListoverArrayListinJava? 3867 HowdoIgeneraterandomintegerswithinaspecificrangeinJava? 3323 HowdoIconvertaStringtoanintinJava? 3536 HowcanIcreateamemoryleakinJava? 3859 ProperusecasesforAndroidUserManager.isUserAGoat()? HotNetworkQuestions HowcanPlanck'sconstanttakedifferentvalues? HowcanIrepairasnapped4x4mailboxpostwithoutdiggingoutthefooting? HowtodraworcreatearoundedrectangleinBlenderusingcurves(notaplane/cube)? IsEQtheonlyreasonpickupssounddifferent? GolfConway'sPrimordialStill-Life Whatdoestheoutputofgcc--versionmean Howdoisay“holdthebus?” WhathappenswhenbothplayerscontrolaLiesa,ForgottonArchangel? Compressanddecompress HowshouldIfollowupwiththisprofessor? DotheUvaluesaffectstructureoptimizationwiththeDFT+Usimulationtooptimizecrystalstructure? HowcanaScrumdailynotbeastatuspull? Whatkindofmatterispositronium? Howdoweexpresswewantsomeonetodowhatwesaywithoutanynegotiation? NIntegrate:theorderofsingularpointsmatters! Whatistheideabehind"pornotp"beingatautology? WhatlanguagedidGaiusJuliusCaesarspeakwithCleopatra? Meaningof"tappedontheshoulder" DoesNorthKoreagetpermissiontotest-flyweaponsoverChinaandRussia?(ifitindeeddoes) Doespayingoffallcreditaccountsworsenyourscore? Replyingtostudents'emailsorignoringirrelevantquestions Whatisthebenefitofregressionwithstudent-tresidualsoverOLSregression? Whatisthebestwaytoremovelargeamountsofrubblefromabackyardwithnarrowaccess(1.2mwide)andasteep(30degree)driveway? HowdoesAustraliasplititslegalprofession? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-java Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?