Java - Constructors - Tutorialspoint
文章推薦指數: 80 %
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
延伸文章資訊
- 1初始化物件Constructor - Java備忘筆記 - GitBook
- 2Java Constructor - Javatpoint
In Java, a constructor is a block of codes similar to the method. It is called when an instance o...
- 3Java Constructors - Tutorials Jenkov
- 4Constructor (Java Platform SE 8 ) - Oracle Help Center
public final class Constructor<T> extends Executable. Constructor provides information about, ......
- 5Why We Use Constructor in Java - Javatpoint