Java Reference
In-Depth Information
The Mechanics of Methods
When you write a method, it becomes available for invocation according to its
signature
. The
Javaâ„¢Language Specification
(Gosling et al. 2000) says: "The
signature
of a method consists
of the name of the method and the number and types of formal parameters to the method" (p.
169).
Note that a method's signature does not include return type. However, if a method declaration
overrides the declaration of another method, a compile-time error occurs if they have different
return types.
CHALLENGE 20.3
At Oozinoz, the method
MachineSimulator.clone()
returns
Object
, even
though the method always returns an instance of
MachineSimulator
. Will this
method be more effective if you change it to return
MachineSimulator
?
A signature specifies which method is invoked when a client makes a call. So how is
signature
different from
operation?
After all, both terms refer to the specification of a service.
The terms differ mainly in the context in which they are typically used. The term
operation
applies when discussing the idea that methods in different classes may have the same
interface. The term
signature
applies when discussing the rules that govern how Java matches
a method call to a method in the receiving object.
In Java, a method declaration includes a
header
and a
body.
A method's body is the series of
instructions that can be called into action by invoking the method's signature. A method's
header
includes the method's return type and signature and may include modifiers and a
throws
clause. The form of a method header is:
modifiers type signature throws-clause
Each of the four aspects of a method's header contains subtleties and challenges.
Method modifiers include visibility modifiers:
abstract
,
static
,
final
,
synchronized
, and
native
. Several earlier chapters have discussed visibility and
the
abstract
modifier. The remaining modifiers are all important, of course, but only
static
appears frequently when implementing the patterns this topic describes.
A static method is invoked without reference to a particular object. This can lead to surprising
results. Consider the classes
Firework
and
Rocket
in Figure 20.2. Each class defines
a static
flies()
method. Most fireworks don't fly, so
Firework
defines this to return
false
, whereas
Rocket
defines it to return
true
.