|
Methods, similar to
functions
in other languages, are a mechanism for
program decomposition
. They provide a way to group together statements that perform a particular operation. If your program executes the operation repeatedly, you need only call method that executes that operation rather than repeatedly writing several statements to perform the operation.
Each method has a signature that specifies its name and the type, number, and order of its parameters . Parameters are the inputs to a method. A method header includes the information provided in the signature, along with the return value of the method. It may also (optionally) specify a visibility modifier . This indicates from where the method can be called. The modifier public indicates that the method may be called from anywhere. The modifier private indicates that the method may only be called from other methods in the same class. Example: public int addOne(int input) Calling MethodsA method is called on an object. To call a method you specify the name of the variable that stores a reference to the object, followed by the dot operator , followed by the name of the method, followed by the parameters it accepts enclosed in parentheses. If the method accepts no parameters, you use empty parentheses. |