Providing Constructors for Your Classes (The Java™ Tutorials ...
文章推薦指數: 80 %
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.Constructordeclarationslooklikemethoddeclarationsexceptthattheyusethenameoftheclassandhavenoreturntype.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
延伸文章資訊
- 1Java Constructor - Javatpoint
In Java, a constructor is a block of codes similar to the method. It is called when an instance o...
- 2Java Gossip: 建構方法(Constructor) - OpenHome.cc
下面這個程式示範如何使用自訂的安全陣列類別:. UseConstructor.java. public class UseConstructor { public static void mai...
- 3Java - Constructors - Tutorialspoint
Java - Constructors ... A constructor initializes an object when it is created. It has the same n...
- 4Providing Constructors for Your Classes (The Java™ Tutorials ...
As with methods, the Java platform differentiates constructors on the basis of the number of argu...
- 5Why We Use Constructor in Java - Javatpoint