Methods |
| BASIC |
Methods are used to break up a long program into shorter, carefully named, easier to understand pieces.
For example, the following program computes the average of two numbers entered by the user.
public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); double number1 = input.nextDouble(); System.out.print("Enter a number: "); double number2 = input.nextDouble(); double average = (number1 + number2) / 2; System.out.println("The average of " + number1 + " and " + number2 + " is " + average); }
This program is cluttered and difficult to read (blank lines in a couple of
places would help, though). Now consider the main method in the
following equivalent program:
public static void main(String[] args) { double number1 = getANumber(); double number2 = getANumber(); System.out.println("The average of " + number1 + " and " + number2 + " is " + average(number1, number2)); } private static double getANumber() { Scanner input = new Scanner(System.in); System.out.print("Enter a number: "); return input.nextDouble(); } private static double average(double number1, double number2) { return (number1 + number2) / 2; }
You probably found the main method easier to read in this second version. It
is shorter, uses meaningful names (getANumber, average)
to help explain what is being done, and avoids duplication of the three lines
involved in reading a number. In the above,
main method "calls" getANumber()
to get a double value, and assigns this value to number1.main method "calls" getANumber()
a second time to get another double value, and assigns this value
to number2.main method calls average(number1, number2)
to compute the average of the two numbers.main method concatenates this average value with some Strings,
and calls another method System.out.println to display the result.Basically, all the other methods act as "helpers" to the main
method: They scurry around and do whatever main asks them to do.
These other methods may call helper minput.nextDouble()ethods of
their own, to any level (for example, the getANumber() method above
uses as a helper method).
Here is the (slightly simplified) syntax for a method definition:
access optionalStatic returnType methodName(formalParameters) { declarations; statements; return expression; }
where:
public, protected,
package (default; no keyword used), or private, to indicate what
other code may use the method.
optionalStatic is the keyword static for
static methods, omitted for non-static methods.
Very few of your methods should be static; static methods were used here to
simplify the example.
returnType is the type of
value returned by the method, if any. Methods may return any valid type, or
void if no type is to be returned.
methodName is a name you choose to describe, as accurately
as possible, what the method does.
formalParameters is a list of variable declarations that
describe what information must be given to the method. Each parameter consists
of a type and a variable. The type of the formal
parameters (in this case, double)
must be able to hold the values given in the call to the method. In this
example the parameter names (number1, number2)
happen to be the same in both the main method and the average method,
but this is not necessary.
declarations and statements
are just ordinary Java code. The statements may use any
instance variables or static variables of the class, the formal parameters,
or any variables declared within the method.
expression
in the return statement must be a value of the correct
type.
void, the return statement
may be omitted (the method will return when it has reached the closing brace);
if present, it must be written as simply: return;return statements as you like in a method;
they don't have to go at the end.Methods may be static methods or instance methods. You can call a static method by first naming the class to which the method belongs:
SomeClass.someMethod(actualParameters)
The class name may be omitted if the method call is in the same class as the method definition.
Instance methods are "called" by first naming the object to which you want to send a message:
someObject.someMethod(actualParameters)
The object name may be omitted when an object is "talking to itself."
That is, a non-static method may call another non-static
method in the same class, and both methods will be executed by the same object.
Here's how a method call works:
actualParameters (a list of zero or more expressions)
are evaluated.
System.out.println),
any value returned by the method will be ignored. Methods intended to
be used in this way typically return void.When you define a method, you must specify the type of each formal parameter; but when you call a method, you do not specify the types of the actual parameters. For example,
showValue("pi", Math.PI); // method call
public void showValue(String name, double number) { // method definition System.out.println("The value of " + name + " is " + number); }
| STYLE |
The names of methods should be verbs or verb phrases. They should begin with a lowercase letter; if the name consists of multiple words, all but the first should be capitalized. Do not use dollar signs or underscores in the name.
The name should describe as accurately as possible what the method does. If what the method does is too complicated to be given a simple, accurate name, then you should break the method up into simpler, more easily named methods.
Methods should generally be short, preferably short enough to see the entire method at once on your computer screen. There is no such thing as a method that is "too short."
| INTERMEDIATE |
Polymorphism (overloading and overriding methods)
The signature of a method is that which distinguishes it from other methods. In Java, the signature consists of the name of the method, the number of parameters, and the types (in order) of those parameters.
You can have multiple methods in a class with the same name, as long as they have different signatures. This is called overloading the method name.
If a class inherits a method from some superclass, but declares its own method
with the exact same signature, this called overriding the inherited method.
"Calls" to the method will use the non-inherited version. (If, however,
within the class, you wish to use the inherited version, you can prefix it with
the keyword super, for example, super.someMethod()).
Exceptions
Any method which may cause a checked exception to occur must either catch that exception with a try statement, or the method must declare that it throws the exception; for example,
public double sqrt(double arg) throws IllegalArgumentException { ... }
If the method may throw more than one type of checked exception, the exception names are separated by commas.
| ADVANCED |
Parameters must be assignment compatible. In other words, it must be
possible to assign the actual parameter value to the formal parameter variable
without an explicit cast. For example, if the
method definition takes a double formal
parameter, and the method "call" has
an
int actual parameter, the call succeeds, because an int
value can be assigned to a double variable.
If the method is overloaded so that one two or more versions are assignment compatible with the actual parameters of a method call, Java chooses the "best match" version to execute. If there is no clear best match, then the call is ambiguous and results in a syntax error.