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 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
延伸文章資訊
- 1Java 入門指南- getter 與setter - 程式語言教學誌
Java 入門指南- getter 與setter ; 封裝, encapsulation ; 物件, object ; 類別, class ; 宣告, declare.
- 2Getter、Setter的用與不用
有人將罪過推給了JavaBean對Getter、Setter做了規範,然而,若問題根源的確是如此,那麼,直接支援特性(Properties)存取語法的語言,又是怎麼一回事呢?
- 3Getter and Setter in Java - GeeksforGeeks
Getter and Setter are methods used to protect your data and make your code more secure. Getter re...
- 4Java Encapsulation and Getters and Setters - W3Schools
- 5建立getter 和setter - IBM
建立getter 和setter. 這個對話框可選取要建立的getter 和setter 方法。 您可從程式檔功能表或選定欄位或類型的快速功能表中使用產生Getter 和Setter,或是類型中...