Providing Constructors for Your Classes (The Java™ Tutorials ...

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

As with methods, the Java platform differentiates constructors on the basis of the number of arguments in the list and their types. Documentation TheJava™Tutorials HideTOC ClassesandObjects Classes DeclaringClasses DeclaringMemberVariables DefiningMethods ProvidingConstructorsforYourClasses PassingInformationtoaMethodoraConstructor Objects CreatingObjects UsingObjects MoreonClasses ReturningaValuefromaMethod UsingthethisKeyword ControllingAccesstoMembersofaClass UnderstandingClassMembers InitializingFields SummaryofCreatingandUsingClassesandObjects QuestionsandExercises QuestionsandExercises NestedClasses InnerClassExample LocalClasses AnonymousClasses LambdaExpressions MethodReferences WhentoUseNestedClasses,LocalClasses,AnonymousClasses,andLambdaExpressions QuestionsandExercises EnumTypes QuestionsandExercises Trail:LearningtheJavaLanguage Lesson:ClassesandObjects Section:Classes HomePage > LearningtheJavaLanguage > ClassesandObjects « Previous • Trail • Next » TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedon'ttakeadvantageofimprovementsintroducedinlaterreleasesandmightusetechnologynolongeravailable.SeeJavaLanguageChangesforasummaryofupdatedlanguagefeaturesinJavaSE9andsubsequentreleases.SeeJDKReleaseNotesforinformationaboutnewfeatures,enhancements,andremovedordeprecatedoptionsforallJDKreleases. ProvidingConstructorsforYourClasses Aclasscontainsconstructorsthatareinvokedtocreateobjectsfromtheclassblueprint.Constructordeclarationslooklikemethoddeclarations—exceptthattheyusethenameoftheclassandhavenoreturntype.Forexample,Bicyclehasoneconstructor: publicBicycle(intstartCadence,intstartSpeed,intstartGear){ gear=startGear; cadence=startCadence; speed=startSpeed; } TocreateanewBicycleobjectcalledmyBike,aconstructoriscalledbythenewoperator: BicyclemyBike=newBicycle(30,0,8); newBicycle(30,0,8)createsspaceinmemoryfortheobjectandinitializesitsfields. AlthoughBicycleonlyhasoneconstructor,itcouldhaveothers,includingano-argumentconstructor: publicBicycle(){ gear=1; cadence=10; speed=0; } BicycleyourBike=newBicycle();invokestheno-argumentconstructortocreateanewBicycleobjectcalledyourBike. BothconstructorscouldhavebeendeclaredinBicyclebecausetheyhavedifferentargumentlists.Aswithmethods,theJavaplatformdifferentiatesconstructorsonthebasisofthenumberofargumentsinthelistandtheirtypes.Youcannotwritetwoconstructorsthathavethesamenumberandtypeofargumentsforthesameclass,becausetheplatformwouldnotbeabletotellthemapart.Doingsocausesacompile-timeerror. Youdon'thavetoprovideanyconstructorsforyourclass,butyoumustbecarefulwhendoingthis.Thecompilerautomaticallyprovidesano-argument,defaultconstructorforanyclasswithoutconstructors.Thisdefaultconstructorwillcalltheno-argumentconstructorofthesuperclass.Inthissituation,thecompilerwillcomplainifthesuperclassdoesn'thaveano-argumentconstructorsoyoumustverifythatitdoes.Ifyourclasshasnoexplicitsuperclass,thenithasanimplicitsuperclassofObject,whichdoeshaveano-argumentconstructor. Youcanuseasuperclassconstructoryourself.TheMountainBikeclassatthebeginningofthis lesson didjustthat.Thiswillbediscussedlater,inthe lesson oninterfacesandinheritance. Youcanuseaccessmodifiersinaconstructor'sdeclarationtocontrolwhichotherclassescancalltheconstructor. Note: IfanotherclasscannotcallaMyClassconstructor,itcannotdirectlycreateMyClassobjects. «Previous • Trail • Next» AboutOracle| ContactUs| LegalNotices| TermsofUse| YourPrivacyRights Copyright©1995,2022Oracleand/oritsaffiliates.Allrightsreserved. Previouspage:DefiningMethods Nextpage:PassingInformationtoaMethodoraConstructor



請為這篇文章評分?