Different ways to create objects in Java - GeeksforGeeks
文章推薦指數: 80 %
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{ Constructor
延伸文章資訊
- 1Creating Objects
Instantiation: The new keyword is a Java operator that creates the object. As discussed below, th...
- 2How to Create Array of Objects in Java? - GeeksforGeeks
We use the Class_Name followed by a square bracket [] then object reference name to create an Arr...
- 3Creating Objects - Learning the Java Language
The new operator instantiates a class by allocating memory for a new object and returning a refer...
- 4Different ways to create objects in Java - GeeksforGeeks
Using the new keyword in java is the most basic way to create an object. This is the most common ...
- 5Java - Object and Classes - Tutorialspoint