Different ways to create objects in Java - GeeksforGeeks

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

Using the new keyword in java is the most basic way to create an object. This is the most common way to create an object in java. Almost 99% of ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#HTMLJavaScriptPHPSQLScalaPerlGoLanguageKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblemsContests ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningJavaScriptSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesClassesandObjectsinJavaUnderstandingClassesandObjectsinJavaInnerClassinJavaAnonymousInnerClassinJavaNestedClassesinJavaJava.util.ObjectsclassinJavaDifferentwaystocreateobjectsinJavaHowareJavaobjectsstoredinmemory?PassingandReturningObjectsinJavaLambdaExpressionsinJava8SerializationandDeserializationinJavawithExampleGarbageCollectioninJavaHowtopreventobjectsofaclassfromGarbageCollectioninJavaCountnumberofaclassobjectscreatedinJavaClassesandObjectsinJavaUnderstandingClassesandObjectsinJavaInnerClassinJavaAnonymousInnerClassinJavaNestedClassesinJavaJava.util.ObjectsclassinJavaDifferentwaystocreateobjectsinJavaHowareJavaobjectsstoredinmemory?PassingandReturningObjectsinJavaLambdaExpressionsinJava8SerializationandDeserializationinJavawithExampleGarbageCollectioninJavaHowtopreventobjectsofaclassfromGarbageCollectioninJavaCountnumberofaclassobjectscreatedinJavaDifferentwaystocreateobjectsinJavaViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: MediumLastUpdated: 13Jun,2022ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle Thereareseveralwaysbywhichwecancreateobjectsofaclassinjavaasweallknowaclassprovidestheblueprintforobjects,youcreateanobjectfromaclass.Thisconceptisunder-ratedandsometimesprovestobebeneficialasthisconceptisbypassedbymanyprogrammersandsometimesevendoaskfrominterviewperceptive.Methods: TherearemanydifferentwaystocreateobjectsinJava.LetuslistthemlaterdiscussinglatertakingindividuallywiththehelpofprogramstoillustrateinternalworkingbywhichwecancreateobjectsinJava.UsingnewkeywordUsingnewinstanceUsingclone()methodUsingdeserializationUsingnewInstance()methodofConstructorclassLetusdiscussthemonebyoneandimplementthesamebyappendingacleanjavaprogramforthesame.Method1:UsingnewkeywordUsingthenewkeywordinjavaisthemostbasicwaytocreateanobject.Thisisthemostcommonwaytocreateanobjectinjava.Almost99%ofobjectsarecreatedinthisway.Byusingthismethodwecancallanyconstructorwewanttocall(noargumentorparameterizedconstructors).ExampleJava//JavaprogramtoIllustrateCreationofObject//Usingnewkeyword //MainclassclassGFG{     //Declaringandinitializingstring    //Custominputstring    Stringname="GeeksForGeeks";     //Maindrivermethod    publicstaticvoidmain(String[]args)    {        //Asusualandmostgenericusedwewill        //becreatingobjectofclassinsidemain()        //usingnewkeyword        GFGobj=newGFG();         //Printanddisplaytheobject        System.out.println(obj.name);    }}OutputGeeksForGeeksMethod2:UsingnewinstanceIfweknowthenameoftheclass&ifithasapublicdefaultconstructorwecancreateanobjectClass.forName.WecanuseittocreatetheObjectofaClass.Class.forNameactuallyloadstheClassinJavabutdoesn’tcreateanyObject.TocreateanObjectoftheClassyouhavetousethenewInstanceMethodoftheClass.ExampleJava//JavaprogramtoIllustrateCreationofObject//UsingnewInstance //MainclassclassGFG{     //Declaringandinitializingstring    Stringname="GeeksForGeeks";     //Maindrivermethod    publicstaticvoidmain(String[]args)    {        //Tryblocktocheckforexceptions        try{             Classcls=Class.forName("GFG");             //Creatingobjectofmainclass            //usinginstancemethod            GFGobj=(GFG)cls.newInstance();             //Printanddisplay            System.out.println(obj.name);        }         //Catchblocktohandletheexceptions         //Catchblock1        //HandlingClassNotFoundException        catch(ClassNotFoundExceptione){             //Displaytheexceptionalongwithlinenumber            //usingprintStacktrace()method            e.printStackTrace();        }         //Catchblock2        //HandlingInstantiationException        catch(InstantiationExceptione){             e.printStackTrace();        }         //Catchblock2        //HandlingIllegalAccessException        catch(IllegalAccessExceptione){             e.printStackTrace();        }    }}Output: GeeksForGeeksMethod3: Usingclone()methodWheneverclone()iscalledonanyobject,theJVMactuallycreatesanewobjectandcopiesallcontentofthepreviousobjectintoit.Creatinganobjectusingtheclonemethoddoesnotinvokeanyconstructor.Inordertousetheclone()methodonanobjectweneedtoimplementCloneableanddefinetheclone()methodinit.ExampleJava//JavaprogramtoIllustrateCreationofObject//Usingclone()method //Mainclass//ImplementingCloneableinterfaceclassGFGimplementsCloneable{     //Method1    @Override    protectedObjectclone()        throwsCloneNotSupportedException    {        //Super()keywordreferstoparentclass        returnsuper.clone();    }     //Declaringandinitializingstring    Stringname="GeeksForGeeks";     //Method2    //maindrivermethod    publicstaticvoidmain(String[]args)    {        GFGobj1=newGFG();         //Tryblocktocheckforexceptions        try{             //Usingtheclone()method            GFGobj2=(GFG)obj1.clone();             //Printanddisplaythemainclassobject            //ascreatedabove            System.out.println(obj2.name);        }         //Catchblocktohandletheexceptions        catch(CloneNotSupportedExceptione){             //Displaytheexception            //usingprintStackTrace()method            e.printStackTrace();        }    }}OutputGeeksForGeeksNote: HerewearecreatingthecloneofanexistingObjectandnotanynewObject.ClassneedtoimplementCloneableInterfaceotherwiseitwillthrowCloneNotSupportedException.Method4:UsingdeserializationWheneverweserializeandthendeserializeanobject,JVMcreatesaseparateobject.Indeserialization,JVMdoesn’tuseanyconstructortocreatetheobject.TodeserializeanobjectweneedtoimplementtheSerializableinterfaceintheclass.Example1Java//JavaProgramIllustrateSerializinganObject //Importinginputoutputclassesimportjava.io.*; //Mainclass//ImplementingtheSerializableinterfaceclassGFGimplementsSerializable{     //Membervariables    privateStringname;    GFG(Stringname)    {        //Thiskeywordreferstocurrentobjectitself        this.name=name;    }     //Maindrivermethod    publicstaticvoidmain(String[]args)    {        //Tryblocktocheckforexceptions        try{            //Creatingobjectofclassinmain()method            GFGd=newGFG("GeeksForGeeks");             FileOutputStreamf                =newFileOutputStream("file.txt");            ObjectOutputStreamoos                =newObjectOutputStream(f);            oos.writeObject(d);            oos.close();             //Freeingupmemoryresources            f.close();        }         //Catchblocktohandletheexceptiona        catch(Exceptione){            //Displaytheexceptionalongwithlinenumber            //usingprintStacktrace()method            e.printStackTrace();        }    }}Output: GeeksForGeeksObjectofDeserializationExampleclassisserializedusingwriteObject()methodandwrittentofile.txtfile.Example2Java//JavaProgramIllustrateCreationofObject//UsingDeserialization //Importinginputoutputclassesimportjava.io.*; //MainclasspublicclassGFG{     //Maindrivermethod    publicstaticvoidmain(String[]args)    {         //Tryblocktocheckforexceptions        try{             GFGd;             //CreatingFileInputStreamclassobject            FileInputStreamf                =newFileInputStream("file.txt");             //CreatingObjectInputStreamclassobject            ObjectInputStreamoos                =newObjectInputStream(f);            d=(DeserializationExample)oos.readObject();        }         //Catchblocktohandletheexceptions        catch(Exceptione){             //Displaytheexceptiononconsole            //usingprintStacjtrace()method            e.printStackTrace();        }         System.out.println(d.name);    }}Output: GeeksForGeeksMethod5:UsingnewInstance()methodoftheconstructorclassThisissimilartothenewInstance()methodofaclass.ThereisonenewInstance()methodinthejava.lang.reflect.Constructorclasswhichwecanusetocreateobjects.Itcanalsocalltheparameterizedconstructor,andprivateconstructorbyusingthisnewInstance()method.BothnewInstance()methodsareknownasreflectivewaystocreateobjects.InfactnewInstance()methodofClassinternallyusesnewInstance()methodofConstructorclass. ExampleJava//JavaprogramtoillustratecreationofObject//usingnewInstance()methodofConstructorclass //Importingrequiredclassesfromjava.langpackageimportjava.lang.reflect.*; //MainclassclassGFG{     //Membervariablesofthisclass    privateStringname;     //Constructorofthisclass    GFG(){}     //Method1    //Tosetnameofthestring    publicvoidsetName(Stringname)    {        //Thismethodreferstocurrentobjectitself        this.name=name;    }     //Maindrivermethod    publicstaticvoidmain(String[]args)    {        //Tryblocktocheckforexceptions        try{            Constructorconstructor                =GFG.class.getDeclaredConstructor();             GFGr=constructor.newInstance();             //Custompassing            r.setName("GeeksForGeeks");            System.out.println(r.name);        }         //Catchblocktohandletheexceptions        catch(Exceptione){             //Displaytheexceptiononconsole            //usingprintStackTrace()method            e.printStackTrace();        }    }}Output: GeeksForGeeksThisarticleiscontributedbySaketKumar.IfyoulikeGeeksforGeeksandwouldliketocontribute,youcanalsowriteanarticleusingwrite.geeksforgeeks.orgormailyourarticletoreview-team@geeksforgeeks.org.SeeyourarticleappearingontheGeeksforGeeksmainpageandhelpotherGeeks.Pleasewritecommentsifyoufindanythingincorrect,orifyouwanttosharemoreinformationaboutthetopicdiscussedabove.MyPersonalNotes arrow_drop_upSave LikePreviousJava.util.ObjectsclassinJavaNext HowareJavaobjectsstoredinmemory?RecommendedArticlesPage:16,Mar2121,Sep2105,Jan2107,Mar2220,Dec2030,Aug2028,Apr1718,May1723,Oct2029,May1922,Aug2005,Sep2020,Sep2025,Oct2028,Dec2018,Jan2125,Mar2117,Apr2123,Oct2109,Nov2112,Jul1602,Sep1719,Feb2116,Dec16ArticleContributedBy:GeeksforGeeksVotefordifficultyCurrentdifficulty: MediumEasy Normal Medium Hard ExpertImprovedBy:ShreyasWaghmaresolankimayanksagartomar9927anikakapoorpraticecodernnr223442adnanirshad158simmytarika5harshiiash2008varshagumber28ArticleTags:JavaPracticeTags:JavaReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?