Java - Constructors - Tutorialspoint

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

Java - Constructors ... A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. JavaTutorial Java-Home Java-Overview Java-EnvironmentSetup Java-BasicSyntax Java-Object&Classes Java-Constructors Java-BasicDatatypes Java-VariableTypes Java-ModifierTypes Java-BasicOperators Java-LoopControl Java-DecisionMaking Java-Numbers Java-Characters Java-Strings Java-Arrays Java-Date&Time Java-RegularExpressions Java-Methods Java-FilesandI/O Java-Exceptions Java-Innerclasses JavaObjectOriented Java-Inheritance Java-Overriding Java-Polymorphism Java-Abstraction Java-Encapsulation Java-Interfaces Java-Packages JavaAdvanced Java-DataStructures Java-Collections Java-Generics Java-Serialization Java-Networking Java-SendingEmail Java-Multithreading Java-AppletBasics Java-Documentation JavaUsefulResources Java-QuestionsandAnswers Java-QuickGuide Java-UsefulResources Java-Discussion Java-Examples SelectedReading UPSCIASExamsNotes Developer'sBestPractices QuestionsandAnswers EffectiveResumeWriting HRInterviewQuestions ComputerGlossary WhoisWho Java-Constructors Advertisements PreviousPage NextPage  Aconstructorinitializesanobjectwhenitiscreated.Ithasthesamenameasitsclassandissyntacticallysimilartoamethod.However,constructorshavenoexplicitreturntype. Typically,youwilluseaconstructortogiveinitialvaluestotheinstancevariablesdefinedbytheclass,ortoperformanyotherstart-upproceduresrequiredtocreateafullyformedobject. Allclasseshaveconstructors,whetheryoudefineoneornot,becauseJavaautomaticallyprovidesadefaultconstructorthatinitializesallmembervariablestozero.However,onceyoudefineyourownconstructor,thedefaultconstructorisnolongerused. Syntax Followingisthesyntaxofaconstructor− classClassName{ ClassName(){ } } Javaallowstwotypesofconstructorsnamely− NoargumentConstructors ParameterizedConstructors NoargumentConstructors AsthenamespecifiesthenoargumentconstructorsofJavadoesnotacceptanyparametersinstead,usingtheseconstructorstheinstancevariablesofamethodwillbeinitializedwithfixedvaluesforallobjects. Example PublicclassMyClass{ Intnum; MyClass(){ num=100; } } Youwouldcallconstructortoinitializeobjectsasfollows publicclassConsDemo{ publicstaticvoidmain(Stringargs[]){ MyClasst1=newMyClass(); MyClasst2=newMyClass(); System.out.println(t1.num+""+t2.num); } } Thiswouldproducethefollowingresult 100100 ParameterizedConstructors Mostoften,youwillneedaconstructorthatacceptsoneormoreparameters.Parametersareaddedtoaconstructorinthesamewaythattheyareaddedtoamethod,justdeclaretheminsidetheparenthesesaftertheconstructor'sname. Example Hereisasimpleexamplethatusesaconstructor− //Asimpleconstructor. classMyClass{ intx; //Followingistheconstructor MyClass(inti){ x=i; } } Youwouldcallconstructortoinitializeobjectsasfollows− publicclassConsDemo{ publicstaticvoidmain(Stringargs[]){ MyClasst1=newMyClass(10); MyClasst2=newMyClass(20); System.out.println(t1.x+""+t2.x); } } Thiswouldproducethefollowingresult− 1020 UsefulVideoCourses Video JavaDateandTimeOnlineTraining 16Lectures 2hours MalharLathkar MoreDetail Video JavaServletOnlineTraining 19Lectures 5hours MalharLathkar MoreDetail Video JavaScriptOnlineTraining 25Lectures 2.5hours AnadiSharma MoreDetail Video JavaOnlineTraining MostPopular 126Lectures 7hours TusharKale MoreDetail Video JavaEssentialTraining 119Lectures 17.5hours MonicaMittal MoreDetail Video JavaEssentialsOnlineTraining 76Lectures 7hours ArnabChakraborty MoreDetail PreviousPage PrintPage NextPage  Advertisements Print  AddNotes  Bookmarkthispage  ReportError  Suggestions Save Close Dashboard Logout



請為這篇文章評分?