Java Class Methods - W3Schools
文章推薦指數: 80 %
Access Methods With an Object · 1) We created a custom Main class with the class keyword. · 2) We created the fullThrottle() and speed() methods in the Main class ... Tutorials References Exercises Videos Menu Login FreeWebsite GetCertified Pro HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP BOOTSTRAP HOWTO W3.CSS C C++ C# REACT R JQUERY DJANGO TYPESCRIPT NODEJS MYSQL 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 LearnDjango LearnTypeScript ServerSide LearnSQL LearnMySQL LearnPHP LearnASP LearnNode.js LearnRaspberryPi LearnGit LearnAWSCloud WebBuilding CreateaWebsiteNEW WhereToStart WebTemplates WebStatistics WebCertificates WebDevelopment CodeEditor TestYourTypingSpeed PlayaCodeGame CyberSecurity Accessibility Blog 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 PythonExercises SQLExercises PHPExercises JavaExercises CExercises C++Exercises C#Exercises jQueryExercises React.jsExercises MySQLExercises Bootstrap5Exercises Bootstrap4Exercises Bootstrap3Exercises NumPyExercises PandasExercises SciPyExercises TypeScriptExercises ExcelExercises RExercises GitExercises KotlinExercises GoExercises Quizzes HTMLQuiz CSSQuiz JavaScriptQuiz PythonQuiz SQLQuiz PHPQuiz JavaQuiz CQuiz C++Quiz C#Quiz jQueryQuiz React.jsQuiz MySQLQuiz Bootstrap5Quiz Bootstrap4Quiz Bootstrap3Quiz NumPyQuiz PandasQuiz SciPyQuiz TypeScriptQuiz XMLQuiz RQuiz GitQuiz KotlinQuiz CyberSecurityQuiz AccessibilityQuiz Courses HTMLCourse CSSCourse JavaScriptCourse FrontEndCourse PythonCourse SQLCourse PHPCourse JavaCourse C++Course C#Course jQueryCourse React.jsCourse Bootstrap4Course Bootstrap3Course NumPyCourse PandasCourse TypeScriptCourse XMLCourse RCourse DataAnalyticsCourse CyberSecurityCourse AccessibilityCourse Certificates HTMLCertificate CSSCertificate JavaScriptCertificate FrontEndCertificate PythonCertificate SQLCertificate PHPCertificate JavaCertificate C++Certificate C#Certificate jQueryCertificate React.jsCertificate MySQLCertificate Bootstrap5Certificate Bootstrap4Certificate Bootstrap3Certificate TypeScriptCertificate XMLCertificate ExcelCertificate DataScienceCertificate CyberSecurityCertificate AccessibilityCertificate × Tutorials References Exercises GetCertified Spaces Videos Shop Pro JavaTutorial JavaHOME JavaIntro JavaGetStarted JavaSyntax JavaOutput JavaComments JavaVariables Variables PrintVariables DeclareMultipleVariables Identifiers JavaDataTypes DataTypes Numbers Booleans Characters Non-primitiveTypes JavaTypeCasting JavaOperators JavaStrings Strings Concatenation NumbersandStrings 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 JavaClassMethods ❮Previous Next❯ JavaClassMethods YoulearnedfromtheJavaMethodschapterthatmethodsaredeclaredwithina class,andthattheyareusedtoperformcertainactions: Example Createa methodnamedmyMethod()inMain: publicclassMain{ staticvoidmyMethod(){ System.out.println("HelloWorld!"); } } myMethod()printsatext(theaction),whenitis called.To callamethod,writethemethod'snamefollowedbytwoparentheses()andasemicolon; Example Insidemain,call myMethod(): publicclassMain{ staticvoidmyMethod(){ System.out.println("HelloWorld!"); } publicstaticvoidmain(String[]args){ myMethod(); } } //Outputs"HelloWorld!" TryitYourself» Staticvs.Public YouwilloftenseeJavaprogramsthathaveeitherstaticorpublic attributesandmethods. Intheexampleabove,wecreatedastatic method,whichmeansthatitcanbeaccessedwithoutcreatinganobjectoftheclass, unlikepublic,whichcanonlybeaccessedby objects: Example Anexampletodemonstratethedifferencesbetweenstaticandpublic methods: publicclassMain{ //Staticmethod staticvoidmyStaticMethod(){ System.out.println("Staticmethodscanbecalledwithoutcreatingobjects"); } //Publicmethod publicvoidmyPublicMethod(){ System.out.println("Publicmethodsmustbecalledbycreatingobjects"); } //Mainmethod publicstaticvoidmain(String[]args){ myStaticMethod();//Callthestaticmethod //myPublicMethod();Thiswouldcompileanerror MainmyObj=newMain();//CreateanobjectofMain myObj.myPublicMethod();//Callthepublicmethodontheobject } } TryitYourself» Note:Youwilllearnmoreaboutthesekeywords(calledmodifiers)intheJavaModifierschapter. AccessMethodsWithanObject Example CreateaCarobjectnamedmyCar.CallthefullThrottle()andspeed() methodsonthemyCarobject,andruntheprogram: //CreateaMainclass publicclassMain{ //CreateafullThrottle()method publicvoidfullThrottle(){ System.out.println("Thecarisgoingasfastasitcan!"); } //Createaspeed()methodandaddaparameter publicvoidspeed(intmaxSpeed){ System.out.println("Maxspeedis:"+maxSpeed); } //Insidemain,callthemethodsonthemyCarobject publicstaticvoidmain(String[]args){ MainmyCar=newMain(); //CreateamyCarobject myCar.fullThrottle(); //CallthefullThrottle()method myCar.speed(200); //Callthespeed()method } } //Thecarisgoingasfastasitcan! //Maxspeedis:200 TryitYourself» Exampleexplained 1)WecreatedacustomMainclasswiththeclasskeyword. 2)WecreatedthefullThrottle()and speed() methodsintheMainclass. 3)ThefullThrottle()methodandthe speed() methodwillprintoutsometext,whentheyarecalled. 4)Thespeed() methodacceptsanintparametercalled maxSpeed-we willusethisin8). 5)InordertousetheMainclassandits methods,weneedtocreateanobjectofthe MainClass. 6)Then,gotothemain()method,whichyouknowbynowisabuilt-in Javamethodthatrunsyourprogram(anycodeinsidemainisexecuted). 7)Byusingthenewkeywordwecreatedanobjectwiththename myCar. 8)Then,wecallthefullThrottle()and speed() methodsonthe myCarobject,andruntheprogramusingthenameoftheobject(myCar),followedbyadot(.),followedbythenameofthemethod(fullThrottle();and speed(200);). Noticethatweaddanintparameterof200insidethe speed()method. Rememberthat.. Thedot(.)isusedtoaccesstheobject'sattributesandmethods. TocallamethodinJava,writethemethodnamefollowedbyasetofparentheses(),followedbyasemicolon(;). Aclassmusthaveamatchingfilename(Mainand Main.java). UsingMultipleClasses LikewespecifiedintheClasseschapter,itis agoodpracticetocreateanobjectofaclassandaccessitinanotherclass. Rememberthatthenameofthejavafileshouldmatchtheclassname.Inthis example,wehavecreatedtwofilesinthesamedirectory: Main.java Second.java Main.java publicclassMain{ publicvoidfullThrottle(){ System.out.println("Thecarisgoingasfastasitcan!"); } publicvoidspeed(intmaxSpeed){ System.out.println("Maxspeedis:"+maxSpeed); } } Second.java classSecond{ publicstaticvoidmain(String[]args){ MainmyCar=newMain(); //CreateamyCarobject myCar.fullThrottle(); //CallthefullThrottle()method myCar.speed(200); //Callthespeed()method } } Whenbothfileshavebeencompiled: C:\Users\YourName>javacMain.java C:\Users\YourName>javacSecond.java RuntheSecond.javafile: C:\Users\YourName>javaSecond Andtheoutputwillbe: Thecarisgoingasfastasitcan! Maxspeedis:200 TryitYourself» ❮Previous Next❯ NEW WejustlaunchedW3Schoolsvideos Explorenow COLORPICKER Getcertifiedbycompletingacoursetoday! w3schoolsCERTIFIED.2022 Getstarted CODEGAME PlayGame
延伸文章資訊
- 1Class Methods in Java | Explained - Linux Hint
In Java, a method is nothing but a block of code/statement that is declared within the class and ...
- 2Methods in Java - GeeksforGeeks
Method Declaration · public: It is accessible in all classes in your application. · protected: It...
- 3Class Method - java.lang.Object - Oracle Help Center
A Method provides information about, and access to, a single method on a class or interface. The ...
- 4Java學習筆記-方法(Method)
Hello, World! 另一個則是不同class的呼叫:. 程式, 輸出. class class_example{ public static void ...
- 5Method in Java - Javatpoint
The method of the class is known as an instance method. It is a non-static method defined in the ...