Java Constructor - Javatpoint

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

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, ... ⇧SCROLLTOTOP Home Java Programs OOPs String Exception Multithreading Collections JavaFX JSP Spring SpringBoot Projects InterviewQuestions JavaTraining BasicsofJava JavaObjectClass JavaOOPsConcepts NamingConvention ObjectandClass Method Constructor statickeyword thiskeyword JavaInheritance Inheritance(IS-A) Aggregation(HAS-A) JavaPolymorphism MethodOverloading MethodOverriding CovariantReturnType superkeyword InstanceInitializerblock finalkeyword RuntimePolymorphism DynamicBinding instanceofoperator JavaAbstraction Abstractclass Interface AbstractvsInterface JavaEncapsulation Package AccessModifiers Encapsulation JavaArray JavaArray JavaOOPsMisc Objectclass ObjectCloning Mathclass WrapperClass JavaRecursion CallByValue strictfpkeyword javadoctool CommandLineArg ObjectvsClass OverloadingvsOverriding JavaString JavaRegex ExceptionHandling JavaInnerclasses JavaMultithreading JavaI/O JavaNetworking JavaAWT&Events JavaSwing JavaFX JavaApplet JavaReflection JavaDate JavaConversion JavaCollection JavaJDBC JavaNewFeatures RMI Internationalization InterviewQuestions next→ ←prev ConstructorsinJava Typesofconstructors DefaultConstructor ParameterizedConstructor ConstructorOverloading Doesconstructorreturnanyvalue? Copyingthevaluesofoneobjectintoanother Doesconstructorperformothertasksinsteadoftheinitialization InJava,aconstructorisablockofcodessimilartothemethod.Itiscalledwhenaninstanceoftheclassiscreated.Atthetimeofcallingconstructor,memoryfortheobjectisallocatedinthememory. Itisaspecialtypeofmethodwhichisusedtoinitializetheobject. Everytimeanobjectiscreatedusingthenew()keyword,atleastoneconstructoriscalled. Itcallsadefaultconstructorifthereisnoconstructoravailableintheclass.Insuchcase,Javacompilerprovidesadefaultconstructorbydefault. TherearetwotypesofconstructorsinJava:no-argconstructor,andparameterizedconstructor. Note:Itiscalledconstructorbecauseitconstructsthevaluesatthetimeofobjectcreation.Itisnotnecessarytowriteaconstructorforaclass.Itisbecausejavacompilercreatesadefaultconstructorifyourclassdoesn'thaveany. RulesforcreatingJavaconstructor Therearetworulesdefinedfortheconstructor. Constructornamemustbethesameasitsclassname AConstructormusthavenoexplicitreturntype AJavaconstructorcannotbeabstract,static,final,andsynchronized Note:Wecanuseaccessmodifierswhiledeclaringaconstructor.Itcontrolstheobjectcreation.Inotherwords,wecanhaveprivate,protected,publicordefaultconstructorinJava. TypesofJavaconstructors TherearetwotypesofconstructorsinJava: Defaultconstructor(no-argconstructor) Parameterizedconstructor JavaDefaultConstructor Aconstructoriscalled"DefaultConstructor"whenitdoesn'thaveanyparameter. Syntaxofdefaultconstructor: (){} Exampleofdefaultconstructor Inthisexample,wearecreatingtheno-argconstructorintheBikeclass.Itwillbeinvokedatthetimeofobjectcreation. //JavaProgramtocreateandcalladefaultconstructor classBike1{ //creatingadefaultconstructor Bike1(){System.out.println("Bikeiscreated");} //mainmethod publicstaticvoidmain(Stringargs[]){ //callingadefaultconstructor Bike1b=newBike1(); } } TestitNow Output: Bikeiscreated Rule:Ifthereisnoconstructorinaclass,compilerautomaticallycreatesadefaultconstructor. Q)Whatisthepurposeofadefaultconstructor? Thedefaultconstructorisusedtoprovidethedefaultvaluestotheobjectlike0,null,etc.,dependingonthetype. Exampleofdefaultconstructorthatdisplaysthedefaultvalues //Letusseeanotherexampleofdefaultconstructor //whichdisplaysthedefaultvalues classStudent3{ intid; Stringname; //methodtodisplaythevalueofidandname voiddisplay(){System.out.println(id+""+name);} publicstaticvoidmain(Stringargs[]){ //creatingobjects Student3s1=newStudent3(); Student3s2=newStudent3(); //displayingvaluesoftheobject s1.display(); s2.display(); } } TestitNow Output: 0null 0null Explanation:Intheaboveclass,youarenotcreatinganyconstructorsocompilerprovidesyouadefaultconstructor.Here0andnullvaluesareprovidedbydefaultconstructor. JavaParameterizedConstructor Aconstructorwhichhasaspecificnumberofparametersiscalledaparameterizedconstructor. Whyusetheparameterizedconstructor? Theparameterizedconstructorisusedtoprovidedifferentvaluestodistinctobjects.However,youcanprovidethesamevaluesalso. Exampleofparameterizedconstructor Inthisexample,wehavecreatedtheconstructorofStudentclassthathavetwoparameters.Wecanhaveanynumberofparametersintheconstructor. //JavaProgramtodemonstratetheuseoftheparameterizedconstructor. classStudent4{ intid; Stringname; //creatingaparameterizedconstructor Student4(inti,Stringn){ id=i; name=n; } //methodtodisplaythevalues voiddisplay(){System.out.println(id+""+name);} publicstaticvoidmain(Stringargs[]){ //creatingobjectsandpassingvalues Student4s1=newStudent4(111,"Karan"); Student4s2=newStudent4(222,"Aryan"); //callingmethodtodisplaythevaluesofobject s1.display(); s2.display(); } } TestitNow Output: 111Karan 222Aryan ConstructorOverloadinginJava InJava,aconstructorisjustlikeamethodbutwithoutreturntype.ItcanalsobeoverloadedlikeJavamethods. ConstructoroverloadinginJavaisatechniqueofhavingmorethanoneconstructorwithdifferentparameterlists.Theyarearrangedinawaythateachconstructorperformsadifferenttask.Theyaredifferentiatedbythecompilerbythenumberofparametersinthelistandtheirtypes. ExampleofConstructorOverloading //Javaprogramtooverloadconstructors classStudent5{ intid; Stringname; intage; //creatingtwoargconstructor Student5(inti,Stringn){ id=i; name=n; } //creatingthreeargconstructor Student5(inti,Stringn,inta){ id=i; name=n; age=a; } voiddisplay(){System.out.println(id+""+name+""+age);} publicstaticvoidmain(Stringargs[]){ Student5s1=newStudent5(111,"Karan"); Student5s2=newStudent5(222,"Aryan",25); s1.display(); s2.display(); } } TestitNow Output: 111Karan0 222Aryan25 DifferencebetweenconstructorandmethodinJava Therearemanydifferencesbetweenconstructorsandmethods.Theyaregivenbelow. JavaConstructorJavaMethod Aconstructorisusedtoinitializethestateofanobject.Amethodisusedtoexposethebehaviorofanobject. Aconstructormustnothaveareturntype.Amethodmusthaveareturntype. Theconstructorisinvokedimplicitly.Themethodisinvokedexplicitly. TheJavacompilerprovidesadefaultconstructorifyoudon'thaveanyconstructorinaclass.Themethodisnotprovidedbythecompilerinanycase. Theconstructornamemustbesameastheclassname.Themethodnamemayormaynotbesameastheclassname. JavaCopyConstructor ThereisnocopyconstructorinJava.However,wecancopythevaluesfromoneobjecttoanotherlikecopyconstructorinC++. TherearemanywaystocopythevaluesofoneobjectintoanotherinJava.Theyare: Byconstructor Byassigningthevaluesofoneobjectintoanother Byclone()methodofObjectclass Inthisexample,wearegoingtocopythevaluesofoneobjectintoanotherusingJavaconstructor. //Javaprogramtoinitializethevaluesfromoneobjecttoanotherobject. classStudent6{ intid; Stringname; //constructortoinitializeintegerandstring Student6(inti,Stringn){ id=i; name=n; } //constructortoinitializeanotherobject Student6(Student6s){ id=s.id; name=s.name; } voiddisplay(){System.out.println(id+""+name);} publicstaticvoidmain(Stringargs[]){ Student6s1=newStudent6(111,"Karan"); Student6s2=newStudent6(s1); s1.display(); s2.display(); } } TestitNow Output: 111Karan 111Karan Copyingvalueswithoutconstructor Wecancopythevaluesofoneobjectintoanotherbyassigningtheobjectsvaluestoanotherobject.Inthiscase,thereisnoneedtocreatetheconstructor. classStudent7{ intid; Stringname; Student7(inti,Stringn){ id=i; name=n; } Student7(){} voiddisplay(){System.out.println(id+""+name);} publicstaticvoidmain(Stringargs[]){ Student7s1=newStudent7(111,"Karan"); Student7s2=newStudent7(); s2.id=s1.id; s2.name=s1.name; s1.display(); s2.display(); } } TestitNow Output: 111Karan 111Karan Q)Doesconstructorreturnanyvalue? Yes,itisthecurrentclassinstance(Youcannotusereturntypeyetitreturnsavalue). Canconstructorperformothertasksinsteadofinitialization? Yes,likeobjectcreation,startingathread,callingamethod,etc.Youcanperformanyoperationintheconstructorasyouperforminthemethod. IsthereConstructorclassinJava? Yes. WhatisthepurposeofConstructorclass? JavaprovidesaConstructorclasswhichcanbeusedtogettheinternalinformationofaconstructorintheclass.Itisfoundinthejava.lang.reflectpackage. NextTopicstatickeywordinjava ←prev next→ ForVideosJoinOurYoutubeChannel:JoinNow Feedback SendyourFeedbackto[email protected] HelpOthers,PleaseShare LearnLatestTutorials Splunk SPSS Swagger Transact-SQL Tumblr ReactJS Regex ReinforcementLearning RProgramming RxJS ReactNative PythonDesignPatterns PythonPillow PythonTurtle Keras Preparation Aptitude Reasoning VerbalAbility InterviewQuestions CompanyQuestions TrendingTechnologies ArtificialIntelligence AWS Selenium CloudComputing Hadoop ReactJS DataScience Angular7 Blockchain Git MachineLearning DevOps B.Tech/MCA DBMS DataStructures DAA OperatingSystem ComputerNetwork CompilerDesign ComputerOrganization DiscreteMathematics EthicalHacking ComputerGraphics SoftwareEngineering WebTechnology CyberSecurity Automata CProgramming C++ Java .Net Python Programs ControlSystem DataMining DataWarehouse JavatpointServicesJavaTpointofferstoomanyhighqualityservices.Mailuson[email protected],togetmoreinformationaboutgivenservices.WebsiteDesigningWebsiteDevelopmentJavaDevelopmentPHPDevelopmentWordPressGraphicDesigningLogoDigitalMarketingOnPageandOffPageSEOPPCContentDevelopmentCorporateTrainingClassroomandOnlineTrainingDataEntryTrainingForCollegeCampusJavaTpointofferscollegecampustrainingonCoreJava,AdvanceJava,.Net,Android,Hadoop,PHP,WebTechnologyandPython.Pleasemailyourrequirementat[email protected]Duration:1weekto2weekLike/Subscribeusforlatestupdatesornewsletter



請為這篇文章評分?