Getter and Setter in Java - GeeksforGeeks

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

Getter and Setter are methods used to protect your data and make your code more secure. Getter returns the value (accessors), it returns the ... Skiptocontent TutorialsPracticeDS&Algo.MustDoQuestionsDSATopic-wiseDSACompany-wiseAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsGeekontheTopCareersInternshipJobsApplyforJobsPostaJobJOB-A-THONEventsCourses ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningWebDevelopmentSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesArraysinJavaSplit()StringmethodinJavawithexamplesArrays.sort()inJavawithexamplesFor-eachloopinJavaReverseastringinJavaObjectOrientedProgramming(OOPs)ConceptinJavaHowtoiterateanyMapinJavaHashMapinJavawithExamplesInitializeanArrayListinJavaMultidimensionalArraysinJavaArrayListinJavaStackClassinJavaHowtoaddanelementtoanArrayinJava?OverridinginJavaLinkedListinJavaSingletonClassinJavaCollections.sort()inJavawithExamplesInterfacesinJavaClassesandObjectsinJavaSetinJavaQueueInterfaceInJavaInheritanceinJavaCollectionsinJavaMathpow()methodinJavawithExampleHowtodeterminelengthorsizeofanArrayinJava?InitializingaListinJavaPolymorphisminJavaComparetwoStringsinJavaDifferenceBetween==and.equals()MethodinJavaMultithreadinginJavaTableofContentsArraysinJavaSplit()StringmethodinJavawithexamplesArrays.sort()inJavawithexamplesFor-eachloopinJavaReverseastringinJavaObjectOrientedProgramming(OOPs)ConceptinJavaHowtoiterateanyMapinJavaHashMapinJavawithExamplesInitializeanArrayListinJavaMultidimensionalArraysinJavaArrayListinJavaStackClassinJavaHowtoaddanelementtoanArrayinJava?OverridinginJavaLinkedListinJavaSingletonClassinJavaCollections.sort()inJavawithExamplesInterfacesinJavaClassesandObjectsinJavaSetinJavaQueueInterfaceInJavaInheritanceinJavaCollectionsinJavaMathpow()methodinJavawithExampleHowtodeterminelengthorsizeofanArrayinJava?InitializingaListinJavaPolymorphisminJavaComparetwoStringsinJavaDifferenceBetween==and.equals()MethodinJavaMultithreadinginJavaImproveArticle SaveArticle LikeArticle GetterandSetterinJavaDifficultyLevel: EasyLastUpdated: 24Feb,2022GetterandSetteraremethodsusedtoprotectyourdataandmakeyourcodemoresecure.Getterreturnsthevalue(accessors),itreturnsthevalueofdatatypeint,String,double,float,etc.Fortheconvenienceoftheprogram,getterstartswiththeword“get”followedbythevariablename.WhileSettersetsorupdatesthevalue(mutators).Itsetsthevalueforanyvariablewhichisusedintheprogramsofaclass.andstartswiththeword“set”followedbythevariablename.GetterandSettermaketheprogrammerconvenientinsettingandgettingthevalueforaparticulardatatype.Inbothgetterandsetter,thefirstletterofthevariableshouldbecapital.Example1Java//JavaProgramtoIllustrateGetterandSetter //Importinginputoutputclassesimportjava.io.*; //Class1//HelperclassclassGetSet{     //Membervariableofthisclass    privateStringname;     //Method1-Getter    publicStringgetName(){returnname;}     //Method2-Setter    publicvoidsetName(StringN)    {         //Thiskeywordreferstocurrentinstanceitself        this.name=N;    }} //Class2//MainclassclassGFG{     //Maindrivermethod    publicstaticvoidmain(String[]args)    {        //Creatinganobjectofclass1inmain()method        GetSetobj=newGetSet();         //Settingthenamebycallingsettermethod        obj.setName("GeeksforGeeks");        //Gettingthenamebycallinggetermethod        System.out.println(obj.getName());    }}OutputGeeksforGeeksGetterandSettergiveyoutheconveniencetoenterthevalueofthevariablesofanydatatypeasperaccordancewiththerequirementofthecode.Gettersandsettersletyoumanagehowcrucialvariablesinyourcodeareaccessedandaltered.Itcanbeseenasintheprogrambeendiscussedbelowasfollows:Example2Java//JavaProgramtoIllustrateGetterandSetter //Importinginputoutputclassesimportjava.io.*; classGetSet{     //Membervariableofthisclass    privateintnum;     //Method1-Setter    publicvoidsetNumber(intnumber)    {         //Checkingifnumberifbetween1to10exclusive        if(number<1||number>10){             thrownewIllegalArgumentException();        }        num=number;    }     //Method2-Getter    publicintgetNumber(){returnnum;}} //Class2//MainclassclassGFG{     //Maindrivermethod    publicstaticvoidmain(String[]args)    {        GetSetobj=newGetSet();         //Callingmethod1insidemain()method        obj.setNumber(5);         //Printingthenumberassettedabove        System.out.println(obj.getNumber());    }}Output0Outputexplanation:Herewecanseethatifwetakeavaluegreaterthan10thenitshowsanerror,ByusingthesetNumber()method,onecanbesurethevalueofanumberisalwaysbetween1and10.Thisismuchbetterthanupdatingthenumbervariabledirectly.Note:ThiscouldbeavoidedbymakingthenumberaprivatevariableandutilizingthesetNumbermethod.Usingagettermethod,ontheotherhand,isthesolewaytoreadanumber’svalue.MyPersonalNotes arrow_drop_upSave LikePreviousJava-ExceptionHandlingWithConstructorsinInheritanceNext Privacy,securityandsocialimpactsofDataMiningRecommendedArticlesPage:02,Mar2117,Nov2121,Mar2101,Feb2201,Feb2215,Feb2215,Feb2215,Feb2225,Feb2209,Mar2207,Apr2102,Feb2105,Jan2123,Mar2130,Oct1701,Nov1720,Nov1724,Nov1724,Nov1717,May1827,Feb2021,May2030,Jun2019,Feb21ArticleContributedBy:sachinyadavshiv8@sachinyadavshiv8VotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:mehtayash2001ArticleTags:JavaPracticeTags:JavaReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinJavaBestWayToStartLearningCoreJava–ACompleteRoadmapStreamInJavaIntroductiontoJavaDifferentwaysofReadingatextfileinJavaGenericsinJavaMorerelatedarticlesinJavaConstructorsinJavaFunctionalInterfacesinJavaComparatorInterfaceinJavawithExamplesPriorityQueueinJavaStringsinJava× Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?