Getter and Setter in Java - GeeksforGeeks
文章推薦指數: 80 %
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
延伸文章資訊
- 1Getter、Setter的用與不用 - iThome
有人將罪過推給了JavaBean對Getter、Setter做了規範,然而,若問題根源的確是如此,那麼,直接支援特性(Properties)存取語法的語言,又是怎麼一回事呢?
- 2属性的getter 和setter - 现代JavaScript 教程
访问器属性由“getter” 和“setter” 方法表示。在对象字面量中,它们用 get 和 set 表示:. let obj = { get propName() { // 当读取obj.
- 3@Getter and @Setter - Project Lombok
You can also put a @Getter and/or @Setter annotation on a class. In that case, it's as if you ann...
- 4建立getter 和setter - IBM
建立getter 和setter. 這個對話框可選取要建立的getter 和setter 方法。 您可從程式檔功能表或選定欄位或類型的快速功能表中使用產生Getter 和Setter,或是類型中...
- 5Getters and Setters in Java Explained - freeCodeCamp
Getters and setters are used to protect your data, particularly when creating classes. For each i...