Method in Java - Javatpoint
文章推薦指數: 80 %
The method of the class is known as an instance method. It is a non-static method defined in the class. Before calling or invoking the instance method, it is ... ⇧SCROLLTOTOP Home Java Programs OOPs String Exception Multithreading Collections JavaFX JSP Spring SpringBoot Projects InterviewQuestions JavaTutorial WhatisJava HistoryofJava FeaturesofJava C++vsJava HelloJavaProgram ProgramInternal Howtosetpath? JDK,JREandJVM JVM:JavaVirtualMachine JavaVariables JavaDataTypes UnicodeSystem Operators Keywords ControlStatements JavaControlStatements JavaIf-else JavaSwitch JavaForLoop JavaWhileLoop JavaDoWhileLoop JavaBreak JavaContinue JavaComments JavaPrograms JavaObjectClass JavaOOPsConcepts NamingConvention ObjectandClass Method Constructor statickeyword thiskeyword JavaInheritance Inheritance(IS-A) Aggregation(HAS-A) JavaPolymorphism MethodOverloading MethodOverriding CovariantReturnType superkeyword InstanceInitializerblock finalkeyword RuntimePolymorphism DynamicBinding instanceofoperator JavaAbstraction Abstractclass Interface AbstractvsInterface JavaEncapsulation Package AccessModifiers Encapsulation JavaArray JavaArray JavaOOPsMisc Objectclass ObjectCloning Mathclass WrapperClass JavaRecursion CallByValue strictfpkeyword javadoctool CommandLineArg ObjectvsClass OverloadingvsOverriding JavaString JavaRegex ExceptionHandling JavaInnerclasses JavaMultithreading JavaI/O JavaNetworking JavaAWT&Events JavaSwing JavaFX JavaApplet JavaReflection JavaDate JavaConversion JavaCollection JavaJDBC JavaMisc JavaNewFeatures RMI Internationalization InterviewQuestions JavaMCQ next→ ←prev MethodinJava Ingeneral,amethodisawaytoperformsometask.Similarly,themethodinJavaisacollectionofinstructionsthatperformsaspecifictask.Itprovidesthereusabilityofcode.Wecanalsoeasilymodifycodeusingmethods.Inthissection,wewilllearnwhatisamethodinJava,typesofmethods,methoddeclaration,andhowtocallamethodinJava. WhatisamethodinJava? Amethodisablockofcodeorcollectionofstatementsorasetofcodegroupedtogethertoperformacertaintaskoroperation.Itisusedtoachievethereusabilityofcode.Wewriteamethodonceanduseitmanytimes.Wedonotrequiretowritecodeagainandagain.Italsoprovidestheeasymodificationandreadabilityofcode,justbyaddingorremovingachunkofcode.Themethodisexecutedonlywhenwecallorinvokeit. ThemostimportantmethodinJavaisthemain()method.Ifyouwanttoreadmoreaboutthemain()method,gothroughthelinkhttps://www.javatpoint.com/java-main-method. MethodDeclaration Themethoddeclarationprovidesinformationaboutmethodattributes,suchasvisibility,return-type,name,andarguments.Ithassixcomponentsthatareknownasmethodheader,aswehaveshowninthefollowingfigure. MethodSignature:Everymethodhasamethodsignature.Itisapartofthemethoddeclaration.Itincludesthemethodnameandparameterlist. AccessSpecifier:Accessspecifierormodifieristheaccesstypeofthemethod.Itspecifiesthevisibilityofthemethod.Javaprovidesfourtypesofaccessspecifier: Public:Themethodisaccessiblebyallclasseswhenweusepublicspecifierinourapplication. Private:Whenweuseaprivateaccessspecifier,themethodisaccessibleonlyintheclassesinwhichitisdefined. Protected:Whenweuseprotectedaccessspecifier,themethodisaccessiblewithinthesamepackageorsubclassesinadifferentpackage. Default:Whenwedonotuseanyaccessspecifierinthemethoddeclaration,Javausesdefaultaccessspecifierbydefault.Itisvisibleonlyfromthesamepackageonly. ReturnType:Returntypeisadatatypethatthemethodreturns.Itmayhaveaprimitivedatatype,object,collection,void,etc.Ifthemethoddoesnotreturnanything,weusevoidkeyword. MethodName:Itisauniquenamethatisusedtodefinethenameofamethod.Itmustbecorrespondingtothefunctionalityofthemethod.Suppose,ifwearecreatingamethodforsubtractionoftwonumbers,themethodnamemustbesubtraction().Amethodisinvokedbyitsname. ParameterList:Itisthelistofparametersseparatedbyacommaandenclosedinthepairofparentheses.Itcontainsthedatatypeandvariablename.Ifthemethodhasnoparameter,lefttheparenthesesblank. MethodBody:Itisapartofthemethoddeclaration.Itcontainsalltheactionstobeperformed.Itisenclosedwithinthepairofcurlybraces. NamingaMethod Whiledefiningamethod,rememberthatthemethodnamemustbeaverbandstartwithalowercaseletter.Ifthemethodnamehasmorethantwowords,thefirstnamemustbeaverbfollowedbyadjectiveornoun.Inthemulti-wordmethodname,thefirstletterofeachwordmustbeinuppercaseexceptthefirstword.Forexample: Single-wordmethodname:sum(),area() Multi-wordmethodname:areaOfCircle(),stringComparision() Itisalsopossiblethatamethodhasthesamenameasanothermethodnameinthesameclass,itisknownasmethodoverloading. TypesofMethod TherearetwotypesofmethodsinJava: PredefinedMethod User-definedMethod PredefinedMethod InJava,predefinedmethodsarethemethodthatisalreadydefinedintheJavaclasslibrariesisknownaspredefinedmethods.Itisalsoknownasthestandardlibrarymethodorbuilt-inmethod.Wecandirectlyusethesemethodsjustbycallingthemintheprogramatanypoint.Somepre-definedmethodsarelength(),equals(),compareTo(),sqrt(),etc.Whenwecallanyofthepredefinedmethodsinourprogram,aseriesofcodesrelatedtothecorrespondingmethodrunsinthebackgroundthatisalreadystoredinthelibrary. Eachandeverypredefinedmethodisdefinedinsideaclass.Suchasprint()methodisdefinedinthejava.io.PrintStreamclass.Itprintsthestatementthatwewriteinsidethemethod.Forexample,print("Java"),itprintsJavaontheconsole. Let'sseeanexampleofthepredefinedmethod. Demo.java publicclassDemo { publicstaticvoidmain(String[]args) { //usingthemax()methodofMathclass System.out.print("Themaximumnumberis:"+Math.max(9,7)); } } Output: Themaximumnumberis:9 Intheaboveexample,wehaveusedthreepredefinedmethodsmain(),print(),andmax().Wehaveusedthesemethodsdirectlywithoutdeclarationbecausetheyarepredefined.Theprint()methodisamethodofPrintStreamclassthatprintstheresultontheconsole.Themax()methodisamethodoftheMathclassthatreturnsthegreateroftwonumbers. Wecanalsoseethemethodsignatureofanypredefinedmethodbyusingthelinkhttps://docs.oracle.com/.Whenwegothroughthelinkandseethemax()methodsignature,wefindthefollowing: Intheabovemethodsignature,weseethatthemethodsignaturehasaccessspecifierpublic,non-accessmodifierstatic,returntypeint,methodnamemax(),parameterlist(inta,intb).Intheaboveexample,insteadofdefiningthemethod,wehavejustinvokedthemethod.Thisistheadvantageofapredefinedmethod.Itmakesprogramminglesscomplicated. Similarly,wecanalsoseethemethodsignatureoftheprint()method. User-definedMethod Themethodwrittenbytheuserorprogrammerisknownasauser-definedmethod.Thesemethodsaremodifiedaccordingtotherequirement. HowtoCreateaUser-definedMethod Let'screateauserdefinedmethodthatchecksthenumberisevenorodd.First,wewilldefinethemethod. //userdefinedmethod publicstaticvoidfindEvenOdd(intnum) { //methodbody if(num%2==0) System.out.println(num+"iseven"); else System.out.println(num+"isodd"); } Wehavedefinedtheabovemethodnamedfindevenodd().Ithasaparameternumoftypeint.Themethoddoesnotreturnanyvaluethat'swhywehaveusedvoid.Themethodbodycontainsthestepstocheckthenumberisevenorodd.Ifthenumberiseven,itprintsthenumberiseven,elseprintsthenumberisodd. HowtoCallorInvokeaUser-definedMethod Oncewehavedefinedamethod,itshouldbecalled.Thecallingofamethodinaprogramissimple.Whenwecallorinvokeauser-definedmethod,theprogramcontroltransfertothecalledmethod. importjava.util.Scanner; publicclassEvenOdd { publicstaticvoidmain(Stringargs[]) { //creatingScannerclassobject Scannerscan=newScanner(System.in); System.out.print("Enterthenumber:"); //readingvaluefromtheuser intnum=scan.nextInt(); //methodcalling findEvenOdd(num); } Intheabovecodesnippet,assoonasthecompilerreachesatlinefindEvenOdd(num),thecontroltransfertothemethodandgivestheoutputaccordingly. Let'scombinebothsnippetsofcodesinasingleprogramandexecuteit. EvenOdd.java importjava.util.Scanner; publicclassEvenOdd { publicstaticvoidmain(Stringargs[]) { //creatingScannerclassobject Scannerscan=newScanner(System.in); System.out.print("Enterthenumber:"); //readingvaluefromuser intnum=scan.nextInt(); //methodcalling findEvenOdd(num); } //userdefinedmethod publicstaticvoidfindEvenOdd(intnum) { //methodbody if(num%2==0) System.out.println(num+"iseven"); else System.out.println(num+"isodd"); } } Output1: Enterthenumber:12 12iseven Output2: Enterthenumber:99 99isodd Let'sseeanotherprogramthatreturnavaluetothecallingmethod. Inthefollowingprogram,wehavedefinedamethodnamedadd()thatsumupthetwonumbers.Ithastwoparametersn1andn2ofintegertype.Thevaluesofn1andn2correspondtothevalueofaandb,respectively.Therefore,themethodaddsthevalueofaandbandstoreitinthevariablesandreturnsthesum. Addition.java publicclassAddition { publicstaticvoidmain(String[]args) { inta=19; intb=5; //methodcalling intc=add(a,b);//aandbareactualparameters System.out.println("Thesumofaandbis="+c); } //userdefinedmethod publicstaticintadd(intn1,intn2)//n1andn2areformalparameters { ints; s=n1+n2; returns;//returningthesum } } Output: Thesumofaandbis=24 StaticMethod Amethodthathasstatickeywordisknownasstaticmethod.Inotherwords,amethodthatbelongstoaclassratherthananinstanceofaclassisknownasastaticmethod.Wecanalsocreateastaticmethodbyusingthekeywordstaticbeforethemethodname. Themainadvantageofastaticmethodisthatwecancallitwithoutcreatinganobject.Itcanaccessstaticdatamembersandalsochangethevalueofit.Itisusedtocreateaninstancemethod.Itisinvokedbyusingtheclassname.Thebestexampleofastaticmethodisthemain()method. Exampleofstaticmethod Display.java publicclassDisplay { publicstaticvoidmain(String[]args) { show(); } staticvoidshow() { System.out.println("Itisanexampleofstaticmethod."); } } Output: Itisanexampleofastaticmethod. InstanceMethod Themethodoftheclassisknownasaninstancemethod.Itisanon-staticmethoddefinedintheclass.Beforecallingorinvokingtheinstancemethod,itisnecessarytocreateanobjectofitsclass.Let'sseeanexampleofaninstancemethod. InstanceMethodExample.java publicclassInstanceMethodExample { publicstaticvoidmain(String[]args) { //Creatinganobjectoftheclass InstanceMethodExampleobj=newInstanceMethodExample(); //invokinginstancemethod System.out.println("Thesumis:"+obj.add(12,13)); } ints; //user-definedmethodbecausewehavenotusedstatickeyword publicintadd(inta,intb) { s=a+b; //returningthesum returns; } } Output: Thesumis:25 Therearetwotypesofinstancemethod: AccessorMethod MutatorMethod AccessorMethod:Themethod(s)thatreadstheinstancevariable(s)isknownastheaccessormethod.Wecaneasilyidentifyitbecausethemethodisprefixedwiththewordget.Itisalsoknownasgetters.Itreturnsthevalueoftheprivatefield.Itisusedtogetthevalueoftheprivatefield. Example publicintgetId() { returnId; } MutatorMethod:Themethod(s)readtheinstancevariable(s)andalsomodifythevalues.Wecaneasilyidentifyitbecausethemethodisprefixedwiththewordset.Itisalsoknownassettersormodifiers.Itdoesnotreturnanything.Itacceptsaparameterofthesamedatatypethatdependsonthefield.Itisusedtosetthevalueoftheprivatefield. Example publicvoidsetRoll(introll) { this.roll=roll; } Exampleofaccessorandmutatormethod Student.java publicclassStudent { privateintroll; privateStringname; publicintgetRoll() //accessormethod { returnroll; } publicvoidsetRoll(introll)//mutatormethod { this.roll=roll; } publicStringgetName() { returnname; } publicvoidsetName(Stringname) { this.name=name; } publicvoiddisplay() { System.out.println("Rollno.:"+roll); System.out.println("Studentname:"+name); } } AbstractMethod Themethodthatdoesnothasmethodbodyisknownasabstractmethod.Inotherwords,withoutanimplementationisknownasabstractmethod.Italwaysdeclaresintheabstractclass.Itmeanstheclassitselfmustbeabstractifithasabstractmethod.Tocreateanabstractmethod,weusethekeywordabstract. Syntax abstractvoidmethod_name(); Exampleofabstractmethod Demo.java abstractclassDemo//abstractclass { //abstractmethoddeclaration abstractvoiddisplay(); } publicclassMyClassextendsDemo { //methodimpelmentation voiddisplay() { System.out.println("Abstractmethod?"); } publicstaticvoidmain(Stringargs[]) { //creatingobjectofabstractclass Demoobj=newMyClass(); //invokingabstractmethod obj.display(); } } Output: Abstractmethod... Factorymethod Itisamethodthatreturnsanobjecttotheclasstowhichitbelongs.Allstaticmethodsarefactorymethods.Forexample,NumberFormatobj=NumberFormat.getNumberInstance(); NextTopicConstructorsinJava ←prev next→ ForVideosJoinOurYoutubeChannel:JoinNow Feedback SendyourFeedbackto[email protected] HelpOthers,PleaseShare LearnLatestTutorials Splunk SPSS Swagger Transact-SQL Tumblr ReactJS Regex ReinforcementLearning RProgramming RxJS ReactNative PythonDesignPatterns PythonPillow PythonTurtle Keras Preparation Aptitude Reasoning VerbalAbility InterviewQuestions CompanyQuestions TrendingTechnologies ArtificialIntelligence AWS Selenium CloudComputing Hadoop ReactJS DataScience Angular7 Blockchain Git MachineLearning DevOps B.Tech/MCA DBMS DataStructures DAA OperatingSystem ComputerNetwork CompilerDesign ComputerOrganization DiscreteMathematics EthicalHacking ComputerGraphics SoftwareEngineering WebTechnology CyberSecurity Automata CProgramming C++ Java .Net Python Programs ControlSystem DataMining DataWarehouse JavatpointServicesJavaTpointofferstoomanyhighqualityservices.Mailuson[email protected],togetmoreinformationaboutgivenservices.WebsiteDesigningWebsiteDevelopmentJavaDevelopmentPHPDevelopmentWordPressGraphicDesigningLogoDigitalMarketingOnPageandOffPageSEOPPCContentDevelopmentCorporateTrainingClassroomandOnlineTrainingDataEntryTrainingForCollegeCampusJavaTpointofferscollegecampustrainingonCoreJava,AdvanceJava,.Net,Android,Hadoop,PHP,WebTechnologyandPython.Pleasemailyourrequirementat[email protected]Duration:1weekto2weekLike/Subscribeusforlatestupdatesornewsletter
延伸文章資訊
- 1Class Method - java.lang.Object - Oracle Help Center
A Method provides information about, and access to, a single method on a class or interface. The ...
- 2Method in Java - Javatpoint
The method of the class is known as an instance method. It is a non-static method defined in the ...
- 3Java Class Methods - W3Schools
Access Methods With an Object · 1) We created a custom Main class with the class keyword. · 2) We...
- 4Methods in Java - GeeksforGeeks
Method Declaration · public: It is accessible in all classes in your application. · protected: It...
- 5[Java] 8-2 static method 與class method - 給你魚竿- 痞客邦
一般class內的method就和class內的變數一樣. 必須先實體化class後才能夠使用. 而static的method的變數和method則是在一開始就給予記憶體空間.