Java Class, methods, instance variables - w3resource

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

Java is object-oriented programming language. Java classes consist of variables and methods (also known as instance members). Java variables are ... home FrontEnd HTML CSS JavaScript HTML5 Schema.org php.js TwitterBootstrap ResponsiveWebDesigntutorial ZurbFoundation3tutorials PureCSS HTML5Canvas JavaScriptCourse Icon Angular Vue Jest Mocha NPM Yarn BackEnd PHP Python Java Node.js Ruby Cprogramming PHPComposer Laravel PHPUnit Database SQL(2003standardofANSI) MySQL PostgreSQL SQLite NoSQL MongoDB Oracle Redis ApolloGraphQL API GooglePlusAPI YoutubeAPI GoogleMapsAPI FlickrAPI Last.fmAPI TwitterRESTAPI DataInterchnage XML JSON Ajax Exercises HTMLCSSExercises JavaScriptExercises jQueryExercises jQuery-UIExercises CoffeeScriptExercises PHPExercises PythonExercises CProgrammingExercises C#SharpExercises JavaExercises SQLExercises OracleExercises MySQLExercises SQLiteExercises PostgreSQLExercises MongoDBExercises TwitterBootstrapExamples Others ExcelTutorials Usefultools GoogleDocsFormsTemplates GoogleDocsSlidePresentations NumberConversions LinuxTutorials Quizzes Articles Home▼JavaTutorialIntroductionJavaProgramStructureJavaPrimitivedatatype▼DevelopmentenvironmentsetupDownloadandInstallJDK,Eclipse(IDE)Compiling,runninganddebuggingJavaprograms▼DeclarationandAccesscontrolClass,methods,instancevariablesJavaPackages▼OOPSConceptsJavaObjectOrientedProgrammingconceptsIs-AandHas-Arelationship▼AssignmentsArrays-2DarrayandMultidimensionarrayWrapperclasses▼OperatorsAssignmentOperatorArithmeticOperatorConditionalOperatorLogicalOperator▼FlowControlSwitchSatementWhileandDoloopForloopJavaBranchingStatements▼ExceptionsHandlingExceptionsCheckedanduncheckedCustomExceptionTrywithresourcefeatureofJava7▼StringClassStringClassImportantmethodsofStringclasswithexampleStringbufferclassandstringbuilderclass▼FileI/OandserializationFileInputandOutputReadingfileWritingfileJavaPropertyFileProcessingJavaSerialization▼JavaCollectionJavaCollectionFrameworkJavaArrayListandVectorJavaLinkedListClassJavaHashSetJavaTreeSetJavaLinkedHashSetJavaMapsJavaUtilityClass▼JavaThreadJavaDefining,InstantiatingandStartingThreadJavaThreadStatesandTransitionsJavaThreadInteractionJavaCodeSynchronization▼JavaPackageUtilLang▼MiscellaneousGarbageCollectioninJavaBigDecimalMethodMore.... JavaClass,methods,instancevariables LastupdateonAugust19202221:50:42(UTC/GMT+8hours) JavaDeclarationandAccessModifiers Allcomputerprogramsconsistoftwoelements:codeanddata.Furthermore,aprogramcanbeconceptuallyorganizedarounditscodeorarounditsdata.Thefirstwayiscalledprocess-orientedmodel.ProcedurallanguagessuchasCemploythismodeltoconsiderablesuccess.Tomanageincreasingcomplexitythesecondapproachcalledobject-orientedprogrammingwasconceived.Anobject-orientedprogramcanbecharacterizedasdatacontrollingaccesstothecode.Javaisobject-orientedprogramminglanguage.Javaclassesconsistofvariablesandmethods(alsoknownasinstancemembers).Javavariablesaretwotypeseitherprimitivetypesorreferencetypes.First,letusdiscusshowtodeclareaclass,variablesandmethodsthenwewilldiscussaccessmodifiers. DeclarationofClass: Aclassisdeclaredbyuseoftheclasskeyword.Theclassbodyisenclosedbetweencurlybraces{and}.Thedataorvariables,definedwithinaclassarecalledinstancevariables.Thecodeiscontainedwithinmethods.Collectively,themethodsandvariablesdefinedwithinaclassarecalledmembersoftheclass. DeclarationofInstanceVariables: Variablesdefinedwithinaclassarecalledinstancevariablesbecauseeachinstanceoftheclass(thatis,eachobjectoftheclass)containsitsowncopyofthesevariables.Thus,thedataforoneobjectisseparateanduniquefromthedataforanother.Aninstancevariablecanbedeclaredpublicorprivateordefault(nomodifier).Whenwedonotwantourvariable’svaluetobechangedout-sideourclassweshoulddeclarethemprivate.publicvariablescanbeaccessedandchangedfromoutsideoftheclass.WewillhavemoreinformationinOOPconcepttutorial.Thesyntaxisshownbelow. DeclarationofMethods: Amethodisaprogrammodulethatcontainsaseriesofstatementsthatcarryoutatask.Toexecuteamethod,youinvokeorcallitfromanothermethod;thecallingmethodmakesamethodcall,whichinvokesthecalledmethod.Anyclasscancontainanunlimitednumberofmethods,andeachmethodcanbecalledanunlimitednumberoftimes.Thesyntaxtodeclaremethodisgivenbelow. Accessmodifiers: Eachobjecthasmembers(memberscanbevariableandmethods)whichcanbedeclaredtohavespecificaccess.Javahas4accessleveland3accessmodifiers.Accesslevelsarelistedbelowintheleasttomostrestrictiveorder. public:Members(variables,methods,andconstructors)declaredpublic(leastrestrictive)withinapublicclassarevisibletoanyclassintheJavaprogram,whethertheseclassesareinthesamepackageorinanotherpackage.Belowscreenshotshowseclipseviewofpublicclasswithpublicmembers. protected:Theprotectedfieldsormethods,cannotbeusedforclassesandInterfaces.Fields,methodsandconstructorsdeclaredprotectedinasuper-classcanbeaccessedonlybysubclassesinotherpackages.Classesinthesamepackagecanalsoaccessprotectedfields,methodsandconstructorsaswell,eveniftheyarenotasubclassoftheprotectedmember’sclass. Default(novalue):Thedefaultaccesslevelisdeclaredbynotwritinganyaccessmodifieratall.Anyclass,field,methodorconstructorthathasnodeclaredaccessmodifierisaccessibleonlybyclassesinthesamepackage. private:Theprivate(mostrestrictive)modifierscanbeusedformembersbutcannotbeusedforclassesandInterfaces.Fields,methodsorconstructorsdeclaredprivatearestrictlycontrolled,whichmeanstheycannotbeaccessedbyanywhereoutsidetheenclosingclass. Javahasmodifiersotherthanaccessmodifierslistedbelow: static:staticcanbeusedformembersofaclass.Thestaticmembersoftheclasscanbeaccessedwithoutcreatinganobjectofaclass.Let'stakeanexampleofVehicleclasswhichhasrun()asastaticmethodandstop()asanon-staticmethod.InMaruticlasswecanseehowtoaccessstaticmethodrun()andnon-staticmethodstop(). final:Thismodifierapplicabletoclass,method,andvariables.Thismodifiertellsthecompilernottochangethevalueofavariableonceassigned.Ifappliedtoclass,itcannotbesub-classed.Ifappliedtoamethod,themethodcannotbeoverriddeninsub-class.Inbelowsample,wecanseecompilererrorswhiletryingtochangethevalueoffiledagebecauseitisdefinedasfinalwhilewecanchangethevalueofnamefield. abstract:Therearesituationsinwhichyouwillwanttodefineasuperclassthatdeclaresthestructureofagivenabstractionwithoutprovidingacompleteimplementationofeverymethod.Thismodifierisapplicabletoclassandmethodsonly.WewilldiscussabstractclassindetailinseparateTutorial. BelowTablesummarizestheaccessmodifiers Modifier class constructor method Data/variables public Yes Yes Yes Yes protected   Yes Yes Yes default Yes Yes Yes Yes private   Yes Yes Yes static     Yes   final Yes   Yes   Let’stakefirstcolumnexampletointerpret.A“class”canhavepublic,default,finalandabstractaccessmodifiers. Summary Accessmodifiershelptoimplementencapsulationprincipleofobjectorientationprogramming. Javahas4accessmodifierspublic,protected,default,private. Javahasothermodifierslikestatic,finalandabstract. Previous:Compiling,runninganddebuggingJavaprograms Next:JavaPackages  SharethisTutorial/Exerciseon:Facebook andTwitter Exercises:WeeklyTop16MostPopularTopics SQLExercises,Practice,Solution-JOINS SQLExercises,Practice,Solution-SUBQUERIES JavaScriptbasic-Exercises,Practice,Solution JavaArray:Exercises,Practice,Solution CProgrammingExercises,Practice,Solution:ConditionalStatement HRDatabase-SORTFILTER:Exercises,Practice,Solution CProgrammingExercises,Practice,Solution:String PythonDataTypes:Dictionary-Exercises,Practice,Solution PythonProgrammingPuzzles-Exercises,Practice,Solution C++Array:Exercises,Practice,Solution JavaScriptconditionalstatementsandloops-Exercises,Practice,Solution C#SharpBasicAlgorithm:Exercises,Practice,Solution PythonLambda-Exercises,Practice,Solution PythonPandasDataFrame:Exercises,Practice,Solution ConversionTools JavaScript:HTMLFormValidation



請為這篇文章評分?