Java Reference
In-Depth Information
Methods
A method is a named sequence of Java statements that can be invoked by other Java
code. When a method is invoked, it is passed zero or more values known as argu‐
ments . The method performs some computations and, optionally, returns a value.
As described earlier in “Expressions and Operators” on page 30 , a method
invocation is an expression that is evaluated by the Java interpreter. Because method
invocations can have side effects, however, they can also be used as expression state‐
ments. This section does not discuss method invocation, but instead describes how
to define methods.
Deining Methods
You already know how to define the body of a method; it is simply an arbitrary
sequence of statements enclosed within curly braces. What is more interesting about
a method is its signature . 3 The signature specifies the following:
• The name of the method
• The number, order, type, and name of the parameters used by the method
• The type of the value returned by the method
• The checked exceptions that the method can throw (the signature may also list
unchecked exceptions, but these are not required)
• Various method modifiers that provide additional information about the
method
A method signature defines everything you need to know about a method before
calling it. It is the method speciication and defines the API for the method. In order
to use the Java platform's online API reference, you need to know how to read a
method signature. And, in order to write Java programs, you need to know how to
define your own methods, each of which begins with a method signature.
A method signature looks like this:
modifiers type name ( paramlist ) [ throws exceptions ]
The signature (the method specification) is followed by the method body (the
method implementation), which is simply a sequence of Java statements enclosed in
curly braces. If the method is abstract (see Chapter 3 ), the implementation is omit‐
ted, and the method body is replaced with a single semicolon.
The signature of a method may also include type variable declarations—such
methods are known as generic methods . Generic methods and type variables are dis‐
cussed in Chapter 4 .
3 In the Java Language Specification, the term “signature” has a technical meaning that is slightly
different than that used here. This topic uses a less formal definition of method signature.
 
Search WWH ::




Custom Search