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 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 ▲RelatedArticlesArraysinJavaSplit()StringmethodinJavawithexamplesArrays.sort()inJavawithexamplesFor-eachloopinJavaReverseastringinJavaObjectOrientedProgramming(OOPs)ConceptinJavaHowtoiterateanyMapinJavaHashMapinJavawithExamplesInitializeanArrayListinJavaArrayListinJavaMultidimensionalArraysinJavaStackClassinJavaInterfacesinJavaOverridinginJavaHowtoaddanelementtoanArrayinJava?LinkedListinJavaSingletonClassinJavaSetinJavaConvertaStringtoCharacterArrayinJavaInheritanceinJavaClassesandObjectsinJavaQueueInterfaceInJavaCollectionsinJavaCollections.sort()inJavawithExamplesInitializingaListinJavaMultithreadinginJavaMathpow()methodinJavawithExamplePolymorphisminJavaPriorityQueueinJavaHowtodeterminelengthorsizeofanArrayinJava?ArraysinJavaSplit()StringmethodinJavawithexamplesArrays.sort()inJavawithexamplesFor-eachloopinJavaReverseastringinJavaObjectOrientedProgramming(OOPs)ConceptinJavaHowtoiterateanyMapinJavaHashMapinJavawithExamplesInitializeanArrayListinJavaArrayListinJavaMultidimensionalArraysinJavaStackClassinJavaInterfacesinJavaOverridinginJavaHowtoaddanelementtoanArrayinJava?LinkedListinJavaSingletonClassinJavaSetinJavaConvertaStringtoCharacterArrayinJavaInheritanceinJavaClassesandObjectsinJavaQueueInterfaceInJavaCollectionsinJavaCollections.sort()inJavawithExamplesInitializingaListinJavaMultithreadinginJavaMathpow()methodinJavawithExamplePolymorphisminJavaPriorityQueueinJavaHowtodeterminelengthorsizeofanArrayinJava?GetterandSetterinJavaViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 05Jul,2022ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle GetterandSetteraremethodsusedtoprotectyourdataandmakeyourcodemoresecure.Getterreturnsthevalue(accessors),itreturnsthevalueofdatatypeint,String,double,float,etc.Fortheprogram’sconvenience,getterstartswiththeword“get”followedbythevariablename.WhileSettersetsorupdatesthevalue(mutators).Itsetsthevalueforanyvariableusedinaclass’sprograms.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());    }}OutputGeeksforGeeksGetterandSettergiveyoutheconvenienceofenteringthevalueofthevariablesofanydatatypebytherequirementofthecode.Gettersandsettersletyoumanagehowcrucialvariablesinyourcodeareaccessedandaltered.Itcanbeseenintheprogramdiscussedbelowasfollows:Example2Java//JavaProgramtoIllustrateGetterandSetter //Importinginputoutputclassesimportjava.io.*; classGetSet{     //Membervariableofthisclass    privateintnum;     //Method1-Setter    publicvoidsetNumber(intnumber)    {         //Checkingifnumberisbetween1to10exclusive        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());    }}Output5Outputexplanation:Herewecanseethatifwetakeavaluegreaterthan10thenitshowsanerror,ByusingthesetNumber()method,onecanbesurethevalueofanumberisalwaysbetween1and10.Thisismuchbetterthanupdatingthenumbervariabledirectly.Note:ThiscouldbeavoidedbymakingthenumberaprivatevariableandutilizingthesetNumbermethod.Usingagettermethod,ontheotherhand,isthesolewaytoreadanumber’svalue.MyPersonalNotes arrow_drop_upSave LikePreviousJava-ExceptionHandlingWithConstructorsinInheritanceNext HowtoHandletheSSL(HTTPs)CertificationPathExceptioninAndroidApplications?RecommendedArticlesPage:02,Mar2101,Feb2221,Mar2117,Nov2101,Feb2215,Feb2215,Feb2215,Feb2225,Feb2209,Mar2207,Apr2102,Feb2105,Jan2123,Mar2130,Oct1701,Nov1720,Nov1724,Nov1724,Nov1717,May1831,Dec1921,May2019,Feb2127,Feb20ArticleContributedBy:sachinyadavshiv8@sachinyadavshiv8VotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:mehtayash2001gulshankumarpal4ayushjhaaj23ArticleTags:JavaPracticeTags:JavaReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?