Method Basics
Programmers write methods, also known as functions, to automate tasks that may need to be performed many times. To take advantage of this pre-written code, there are several things that we need to know:
- The name of the method
- What information, if any, does the method need sent into it(parameters)?
- What information, if any, does the method return?
These three items together make up what is known as a method's signature. Notice, that as users of the method, we need not understand how it accomplishes its task. This concept is called
information hiding. Thus, if a programmer finds a more efficient way to perform a task, they can re-write the method and not effect any calls to the method as long as they do not alter the method's signature.
Another important consideration when calling a method is to know where the method is. Here are some options:
- Methods in the same class can be called using just the method name name (Ex: myMethod()).
- Member methods of other classes must be called from an instance of that class (Ex: str.length()).
- Static methods of other classes(library functions), must be called from the class name ( Ex: Math.sqrt(5)).
When passing information between a program and a method:
- When calling a method that takes parameters, the parameters must be in the same order as the methods signature.
- When a method returns information, that data needs to either be output or stored in a variable.
Java Methods
The signature of a method has several parts:
- access type - which users are allowed to call the method. The access type is public, private or protected. Public methods are accessable by all users. Private methods are accessable only by users in the class. Protected methods are accessable by users in the class and any subclasses.
- operator type - does the method operate on an object or not. The operator type is static if the method does not operate on the variables of an object. Otherwise, it is just left blank.
- return type - the type of information that the method returns. The return type is the type of data that the method will return to the caller. Return types can be int, String, double, etc. Methods that don't return information are labeled void.
- method name - the name of the method. The method name is an identifier of the method. It follows all the rules for naming variables and should describe what the method does.
- parameter list - the types and number of variables that the method expects to receive. The parameter list is the list, including types, of the variables being sent into the method.
Considering all of this information, a typical method header may look like this:
public static void showAge(int age)
This method is accessable by all users, does not use the private variables of a class, does not return any information, is called showAge and expects an int to be sent in.