Java Constructors (With Examples) - Programiz

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

A constructor in Java is similar to a method that is invoked when an object of the class is created. ... Here, Test() is a constructor. It has the same name as ... CourseIndex ExploreProgramiz Python JavaScript C C++ Java Kotlin Swift C# DSA StartLearningJava ExploreJavaExamples PopularTutorials Java"HelloWorld"Program JavaforLoop ArraysinJava InterfacesinJava JavaArrayList Viewalltutorials PopularExamples Checkprimenumber PrinttheFibonacciseries PrintPyramidsandPatterns Multiplytwomatrices Findthestandarddeviation Viewallexamples ReferenceMaterials String ArrayList HashMap Math Viewall LearningPaths Challenges LearnPythonInteractively TryforFree Courses BecomeaPythonMaster BecomeaCMaster ViewallCourses Python JavaScript C C++ Java Kotlin Swift C# DSA StartLearning Java PopularTutorials Java"HelloWorld"Program JavaforLoop ArraysinJava InterfacesinJava JavaArrayList Viewalltutorials ReferenceMaterials String ArrayList HashMap Math Viewall Python JavaScript C C++ Java Kotlin ExploreJavaExamples PopularExamples Checkprimenumber PrinttheFibonacciseries PrintPyramidsandPatterns Multiplytwomatrices Findthestandarddeviation Viewallexamples JavaIntroduction JavaHelloWorld JavaJVM,JREandJDK JavaVariablesandLiterals JavaDataTypes JavaOperators JavaInputandOutput JavaExpressions&Blocks JavaComment JavaFlowControl Javaif...else JavaswitchStatement JavaforLoop Javafor-eachLoop JavawhileLoop JavabreakStatement JavacontinueStatement JavaArrays JavaArrays MultidimensionalArray JavaCopyArray JavaOOP(I) JavaClassandObjects JavaMethods JavaMethodOverloading JavaConstructor JavaStrings JavaAccessModifiers Javathiskeyword Javafinalkeyword JavaRecursion JavainstanceofOperator JavaOOP(II) JavaInheritance JavaMethodOverriding JavasuperKeyword AbstractClass&Method JavaInterfaces JavaPolymorphism JavaEncapsulation JavaOOP(III) Nested&InnerClass JavaStaticClass JavaAnonymousClass JavaSingleton JavaenumClass JavaenumConstructor JavaenumString JavaReflection JavaExceptionHandling JavaExceptions JavaExceptionHandling Javatry...catch Javathrowandthrows JavacatchMultipleExceptions Javatry-with-resources JavaAnnotations JavaAnnotationTypes JavaLogging JavaAssertions JavaList JavaCollectionsFramework JavaCollectionInterface JavaListInterface JavaArrayList JavaVector JavaStack JavaQueue JavaQueueInterface JavaPriorityQueue JavaDequeInterface JavaLinkedList JavaArrayDeque JavaBlockingQueueInterface JavaArrayBlockingQueue JavaLinkedBlockingQueue JavaMap JavaMapInterface JavaHashMap JavaLinkedHashMap JavaWeakHashMap JavaEnumMap JavaSortedMapInterface JavaNavigableMapInterface JavaTreeMap JavaConcurrentMapInterface JavaConcurrentHashMap JavaSet JavaSetInterface JavaHashSet JavaEnumSet JavaLinkedhashSet JavaSortedSetInterface JavaNavigableSetInterface JavaTreeSet JavaAlgorithms JavaIterator JavaListIterator JavaI/OStreams JavaI/OStreams JavaInputStream JavaOutputStream JavaFileInputStream JavaFileOutputStream JavaByteArrayInputStream JavaByteArrayOutputStream JavaObjectInputStream JavaObjectOutputStream JavaBufferedInputStream JavaBufferedOutputStream JavaPrintStream JavaReader/Writer JavaReader JavaWriter JavaInputStreamReader JavaOutputStreamWriter JavaFileReader JavaFileWriter JavaBufferedReader JavaBufferedWriter JavaStringReader JavaStringWriter JavaPrintWriter AdditionalTopics JavaScannerClass JavaTypeCasting Javaautoboxingandunboxing JavaLambdaExpression JavaGenerics JavaFileClass JavaWrapperClass JavaCommandLineArguments RelatedTopics JavaenumConstructor JavathisKeyword Javasuper JavaReflection JavaSingletonClass JavaAbstractClassandAbstractMethods JavaConstructors Inthistutorial,wewilllearnaboutJavaconstructors,theirtypes,andhowtousethemwiththehelpofexamples. WhatisaConstructor? AconstructorinJavaissimilartoamethodthatisinvokedwhenanobjectoftheclassiscreated. UnlikeJavamethods,aconstructorhasthesamenameasthatoftheclassanddoesnothaveanyreturntype.Forexample, classTest{ Test(){ //constructorbody } } Here,Test()isaconstructor.Ithasthesamenameasthatoftheclassanddoesn'thaveareturntype. RecommendedReading:Whydoconstructorsnotreturnvalues Example1:JavaConstructor classMain{ privateStringname; //constructor Main(){ System.out.println("ConstructorCalled:"); name="Programiz"; } publicstaticvoidmain(String[]args){ //constructorisinvokedwhile //creatinganobjectoftheMainclass Mainobj=newMain(); System.out.println("Thenameis"+obj.name); } } Output: ConstructorCalled: ThenameisProgramiz Intheaboveexample,wehavecreatedaconstructornamedMain().Insidetheconstructor,weareinitializingthevalueofthenamevariable. NoticethestatementofcreatinganobjectoftheMainclass. Mainobj=newMain(); Here,whentheobjectiscreated,theMain()constructoriscalled.And,thevalueofthenamevariableisinitialized. Hence,theprogramprintsthevalueofthenamevariablesasProgramiz. TypesofConstructor InJava,constructorscanbedividedinto3types: No-ArgConstructor ParameterizedConstructor DefaultConstructor 1.JavaNo-ArgConstructors Similartomethods,aJavaconstructormayormaynothaveanyparameters(arguments). Ifaconstructordoesnotacceptanyparameters,itisknownasano-argumentconstructor.Forexample, privateConstructor(){ //bodyoftheconstructor } Example2:Javaprivateno-argconstructor classMain{ inti; //constructorwithnoparameter privateMain(){ i=5; System.out.println("Constructoriscalled"); } publicstaticvoidmain(String[]args){ //callingtheconstructorwithoutanyparameter Mainobj=newMain(); System.out.println("Valueofi:"+obj.i); } } Output: Constructoriscalled Valueofi:5 Intheaboveexample,wehavecreatedaconstructorMain().Here,theconstructordoesnotacceptanyparameters.Hence,itisknownasano-argconstructor. Noticethatwehavedeclaredtheconstructorasprivate. Onceaconstructorisdeclaredprivate,itcannotbeaccessedfromoutsidetheclass.So,creatingobjectsfromoutsidetheclassisprohibitedusingtheprivateconstructor. Here,wearecreatingtheobjectinsidethesameclass.Hence,theprogramisabletoaccesstheconstructor.Tolearnmore,visitJavaImplementPrivateConstructor. However,ifwewanttocreateobjectsoutsidetheclass,thenweneedtodeclaretheconstructoraspublic. Example3:Javapublicno-argconstructors classCompany{ Stringname; //publicconstructor publicCompany(){ name="Programiz"; } } classMain{ publicstaticvoidmain(String[]args){ //objectiscreatedinanotherclass Companyobj=newCompany(); System.out.println("Companyname="+obj.name); } } Output: Companyname=Programiz RecommendedReading:JavaAccessModifier 2.JavaParameterizedConstructor AJavaconstructorcanalsoacceptoneormoreparameters.Suchconstructorsareknownasparameterizedconstructors(constructorwithparameters). Example4:Parameterizedconstructor classMain{ Stringlanguages; //constructoracceptingsinglevalue Main(Stringlang){ languages=lang; System.out.println(languages+"ProgrammingLanguage"); } publicstaticvoidmain(String[]args){ //callconstructorbypassingasinglevalue Mainobj1=newMain("Java"); Mainobj2=newMain("Python"); Mainobj3=newMain("C"); } } Output: JavaProgrammingLanguage PythonProgrammingLanguage CProgrammingLanguage Intheaboveexample,wehavecreatedaconstructornamedMain().Here,theconstructortakesasingleparameter.Noticetheexpression, Mainobj1=newMain("Java"); Here,wearepassingthesinglevaluetotheconstructor.Basedontheargumentpassed,thelanguagevariableisinitializedinsidetheconstructor. 3.JavaDefaultConstructor Ifwedonotcreateanyconstructor,theJavacompilerautomaticallycreateano-argconstructorduringtheexecutionoftheprogram.Thisconstructoriscalleddefaultconstructor. Example5:DefaultConstructor classMain{ inta; booleanb; publicstaticvoidmain(String[]args){ //Adefaultconstructoriscalled Mainobj=newMain(); System.out.println("DefaultValue:"); System.out.println("a="+obj.a); System.out.println("b="+obj.b); } } Output: a=0 b=false Here,wehaven'tcreatedanyconstructors.Hence,theJavacompilerautomaticallycreatesthedefaultconstructor. Thedefaultconstructorinitializesanyuninitializedinstancevariableswithdefaultvalues. Type DefaultValue boolean false byte 0 short 0 int 0 long 0L char \u0000 float 0.0f double 0.0d object Referencenull Intheaboveprogram,thevariablesaandbareinitializedwithdefaultvalue0andfalserespectively. Theaboveprogramisequivalentto: classMain{ inta; booleanb; //aprivateconstructor privateMain(){ a=0; b=false; } publicstaticvoidmain(String[]args){ //calltheconstructor Mainobj=newMain(); System.out.println("DefaultValue:"); System.out.println("a="+obj.a); System.out.println("b="+obj.b); } } TheoutputoftheprogramisthesameasExample5. ImportantNotesonJavaConstructors Constructorsareinvokedimplicitlywhenyouinstantiateobjects. Thetworulesforcreatingaconstructorare: Thenameoftheconstructorshouldbethesameastheclass. AJavaconstructormustnothaveareturntype. Ifaclassdoesn'thaveaconstructor,theJavacompilerautomaticallycreatesadefaultconstructorduringrun-time.Thedefaultconstructorinitializesinstancevariableswithdefaultvalues.Forexample,theintvariablewillbeinitializedto0 Constructortypes:No-ArgConstructor-aconstructorthatdoesnotacceptanyargumentsParameterizedconstructor-aconstructorthatacceptsargumentsDefaultConstructor-aconstructorthatisautomaticallycreatedbytheJavacompilerifitisnotexplicitlydefined. Aconstructorcannotbeabstractorstaticorfinal. Aconstructorcanbeoverloadedbutcannotbeoverridden. ConstructorsOverloadinginJava SimilartoJavamethodoverloading,wecanalsocreatetwoormoreconstructorswithdifferentparameters.Thisiscalledconstructorsoverloading. Example6:JavaConstructorOverloading classMain{ Stringlanguage; //constructorwithnoparameter Main(){ this.language="Java"; } //constructorwithasingleparameter Main(Stringlanguage){ this.language=language; } publicvoidgetName(){ System.out.println("ProgrammingLangauage:"+this.language); } publicstaticvoidmain(String[]args){ //callconstructorwithnoparameter Mainobj1=newMain(); //callconstructorwithasingleparameter Mainobj2=newMain("Python"); obj1.getName(); obj2.getName(); } } Output: ProgrammingLanguage:Java ProgrammingLanguage:Python Intheaboveexample,wehavetwoconstructors:Main()andMain(Stringlanguage).Here,boththeconstructorinitializethevalueofthevariablelanguagewithdifferentvalues. Basedontheparameterpassedduringobjectcreation,differentconstructorsarecalledanddifferentvaluesareassigned. Itisalsopossibletocalloneconstructorfromanotherconstructor.Tolearnmore,visitJavaCallOneConstructorfromAnother. Note:Wehaveusedthiskeywordtospecifythevariableoftheclass.Toknowmoreaboutthiskeyword,visitJavathiskeyword. TableofContents WhatisaConstructor? Example:JavaConstructor JavaNo-ArgConstructors JavaParameterizedConstructor JavaDefaultConstructor ImportantNotesonJavaConstructors ConstructorsOverloadinginJava PreviousTutorial: JavaMethods NextTutorial: JavaStrings Shareon: Didyoufindthisarticlehelpful? Sorryaboutthat. Howcanweimproveit? Feedback* Leavethisfieldblank RelatedTutorialsJavaTutorialJavaenumConstructorJavaTutorialJavathisKeywordJavaTutorialJavasuperJavaTutorialJavaReflection GetApp GetJavaApp



請為這篇文章評分?