Java Reference
In-Depth Information
2.6. Methods
A class's
methods
typically contain the code that understands and manip-
ulates an object's state. Some classes have
public
or
protected
fields for
programmers to manipulate directly, but in most cases this isn't a very
good idea (see "
Designing a Class to Be Extended
"
on page
108
)
. Many
objects have tasks that cannot be represented as a simple value to be
read or modified but that require computation.
We have already seen a number of examples of methods in
Chapter 1
all
of our demonstration programs had a
main
method that was executed by
the Java virtual machine. Here is another
main
method that creates a
Body
object and prints out the values of its fields.
class BodyPrint {
public static void main(String[] args) {
Body sun = new Body("Sol", null);
Body earth = new Body("Earth", sun);
System.out.println("Body " + earth.name +
" orbits " + earth.orbits.name +
" and has ID " + earth.idNum);
}
}
A method declaration consists of two parts: the
method header
and the
method body.
The
method header
consists of an optional set of modi-
fiers, an optional set of type parameters, the method return type, the
signature, and an optional
tHRows
clause listing the exceptions thrown by
the method. The method
signature
consists of the method name and the
(possibly empty) parameter type list enclosed in parentheses. All meth-
ods must have a return type and signature. Type parameters are used to
declare
generic methods
and are discussed in
Chapter 11
.
Exceptions and
throws
clauses are discussed in detail in
Chapter 12
.
The
method body
consists of statements enclosed between curly braces.
The method modifiers consist of the following: