Java Encapsulation and Getters and Setters - W3Schools

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

... CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more. ... private = restricted access // Getter public String getName() { return name; } ... Tutorials References Exercises Videos ProNEW Menu Login PaidCourses WebsiteNEW HTML CSS JAVASCRIPT SQL PYTHON PHP BOOTSTRAP HOWTO W3.CSS JAVA JQUERY C++ C# R React Kotlin    Darkmode Darkcode × Tutorials HTMLandCSS LearnHTML LearnCSS LearnRWD LearnBootstrap LearnW3.CSS LearnColors LearnIcons LearnGraphics LearnSVG LearnCanvas LearnHowTo LearnSass DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery JavaScript LearnJavaScript LearnjQuery LearnReact LearnAngularJS LearnJSON LearnAJAX LearnAppML LearnW3.JS Programming LearnPython LearnJava LearnC LearnC++ LearnC# LearnR LearnKotlin LearnGo ServerSide LearnSQL LearnMySQL LearnPHP LearnASP LearnNode.js LearnRaspberryPi LearnGit LearnAWSCloud WebBuilding CreateaWebsiteNEW WhereToStart WebTemplates WebStatistics WebCertificates WebDevelopment CodeEditor TestYourTypingSpeed PlayaCodeGame CyberSecurity Accessibility DataAnalytics LearnAI LearnMachineLearning LearnDataScience LearnNumPy LearnPandas LearnSciPy LearnMatplotlib LearnStatistics LearnExcel LearnGoogleSheets XMLTutorials LearnXML LearnXMLAJAX LearnXMLDOM LearnXMLDTD LearnXMLSchema LearnXSLT LearnXPath LearnXQuery × References HTML HTMLTagReference HTMLBrowserSupport HTMLEventReference HTMLColorReference HTMLAttributeReference HTMLCanvasReference HTMLSVGReference GoogleMapsReference CSS CSSReference CSSBrowserSupport CSSSelectorReference Bootstrap3Reference Bootstrap4Reference W3.CSSReference IconReference SassReference JavaScript JavaScriptReference HTMLDOMReference jQueryReference AngularJSReference AppMLReference W3.JSReference Programming PythonReference JavaReference ServerSide SQLReference MySQLReference PHPReference ASPReference XML XMLDOMReference XMLHttpReference XSLTReference XMLSchemaReference CharacterSets HTMLCharacterSets HTMLASCII HTMLANSI HTMLWindows-1252 HTMLISO-8859-1 HTMLSymbols HTMLUTF-8 × ExercisesandQuizzes Exercises HTMLExercises CSSExercises JavaScriptExercises SQLExercises MySQLExercises PHPExercises PythonExercises NumPyExercises PandasExercises SciPyExercises jQueryExercises JavaExercises C++Exercises C#Exercises RExercises KotlinExercises GoExercises BootstrapExercises Bootstrap4Exercises Bootstrap5Exercises GitExercises Quizzes HTMLQuiz CSSQuiz JavaScriptQuiz SQLQuiz MySQLQuiz PHPQuiz PythonQuiz NumPyQuiz PandasQuiz SciPyQuiz jQueryQuiz JavaQuiz C++Quiz C#Quiz RQuiz XMLQuiz CyberSecurityQuiz BootstrapQuiz Bootstrap4Quiz Bootstrap5Quiz AccessibilityQuiz Courses HTMLCourse CSSCourse JavaScriptCourse FrontEndCourse SQLCourse PHPCourse PythonCourse NumPyCourse PandasCourse DataAnalyticsCourse jQueryCourse JavaCourse C++Course C#Course RCourse XMLCourse CyberSecurityCourse AccessibilityCourse Certificates HTMLCertificate CSSCertificate JavaScriptCertificate FrontEndCertificate SQLCertificate PHPCertificate PythonCertificate DataScienceCertificate Bootstrap3Certificate Bootstrap4Certificate jQueryCertificate JavaCertificate C++Certificate ReactCertificate XMLCertificate × Tutorials References Exercises PaidCourses Spaces Videos Shop Pro JavaTutorial JavaHOME JavaIntro JavaGetStarted JavaSyntax JavaComments JavaVariables Variables PrintVariables DeclareMultipleVariables Identifiers JavaDataTypes DataTypes Numbers Booleans Characters Non-primitiveTypes JavaTypeCasting JavaOperators JavaStrings Strings SpecialCharacters JavaMath JavaBooleans JavaIf...Else If...Else ShortHandIf...Else JavaSwitch JavaWhileLoop JavaForLoop ForLoop For-EachLoop JavaBreak/Continue JavaArrays Arrays LoopThroughanArray MultidimensionalArrays JavaMethods JavaMethods JavaMethodParameters JavaMethodOverloading JavaScope JavaRecursion JavaClasses JavaOOP JavaClasses/Objects JavaClassAttributes JavaClassMethods JavaConstructors JavaModifiers JavaEncapsulation JavaPackages/API JavaInheritance JavaPolymorphism JavaInnerClasses JavaAbstraction JavaInterface JavaEnums JavaUserInput JavaDate JavaArrayList JavaLinkedList JavaHashMap JavaHashSet JavaIterator JavaWrapperClasses JavaExceptions JavaRegEx JavaThreads JavaLambda JavaFileHandling JavaFiles JavaCreate/WriteFiles JavaReadFiles JavaDeleteFiles JavaHowTo AddTwoNumbers JavaReference JavaKeywords abstract boolean break byte case catch char class continue default do double else enum extends final finally float for if implements import instanceof int interface long new package private protected public return short static super switch this throw throws try void while JavaStringMethods JavaMathMethods JavaExamples JavaExamples JavaCompiler JavaExercises JavaQuiz JavaCertificate JavaEncapsulation ❮Previous Next❯ Encapsulation ThemeaningofEncapsulation,istomakesurethat"sensitive"dataishidden fromusers.Toachievethis,youmust: declareclassvariables/attributesasprivate providepublicget andsetmethodstoaccessandupdatethevalueofaprivate variable GetandSet Youlearnedfromthepreviouschapterthatprivatevariablescanonlybe accessedwithinthesameclass(anoutsideclasshasnoaccesstoit).However, itispossibletoaccessthemifweprovidepublicgetandsetmethods. Thegetmethodreturnsthevariablevalue,andthesetmethodsetsthevalue. Syntaxforbothisthattheystartwitheithergetorset,followedbythe nameofthevariable,withthefirstletterinuppercase: Example publicclassPerson{  privateStringname;//private=restrictedaccess  //Getter  publicStringgetName(){    returnname;  }  //Setter  publicvoidsetName(StringnewName){    this.name=newName;  } } Exampleexplained Thegetmethodreturnsthevalueofthevariablename. Thesetmethodtakesaparameter(newName)andassignsittothe namevariable.Thethiskeywordisusedtorefertothecurrent object. However,asthenamevariableisdeclaredasprivate,we cannotaccessitfromoutsidethisclass: Example publicclassMain{  publicstaticvoidmain(String[]args){    PersonmyObj=newPerson();    myObj.name="John"; //error    System.out.println(myObj.name);//error   } } RunExample» Ifthevariablewasdeclaredaspublic,wewouldexpectthefollowingoutput: John However,aswetrytoaccessaprivatevariable,wegetanerror: MyClass.java:4:error:namehasprivateaccessinPerson     myObj.name="John";          ^ MyClass.java:5:error:namehasprivateaccessinPerson     System.out.println(myObj.name);                   ^ 2errors Instead,weusethegetName()andsetName()methodstoaccessandupdatethevariable: Example publicclassMain{  publicstaticvoidmain(String[]args){    PersonmyObj=newPerson();    myObj.setName("John");//Setthevalueofthenamevariableto"John"    System.out.println(myObj.getName());  } } //Outputs"John" TryitYourself» WhyEncapsulation? Bettercontrolofclassattributesandmethods Classattributescanbemaderead-only(ifyouonlyusethegetmethod),orwrite-only(ifyouonlyusethesetmethod) Flexible:theprogrammercanchangeonepartofthecodewithoutaffectingotherparts Increasedsecurityofdata ❮Previous Next❯ NEW WejustlaunchedW3Schoolsvideos Explorenow COLORPICKER Getcertifiedbycompletingacoursetoday! w3schoolsCERTIFIED.2022 Getstarted CODEGAME PlayGame



請為這篇文章評分?