Programming and Problem Solving with Java

(やまだぃちぅ) #1
2.4 Classes and Methods | 79

Methods


We’ve already seen that a method consists of a method heading plus a block that can con-
tain declarations and executable statements. Between the parentheses in a method head-
ing are the method’s parameters. We will examine the syntax of parameters in more detail
in a later chapter. For now, simply recognize that a parameter is made up of two parts: a
data type or class name, and an identifier (just like a field declaration).
Whereas field declarations end with a semicolon, parameters are listed between the
parentheses with commas separating them. For now, we can think of the parameters as a spe-
cial kind of local field within the method. When a method is called, the arguments from the
method call are copied into the method’s parameters.
Here’s an example of a method heading, showing a list of three parameters.


voidprepareName(String arg1, String arg1, chararg3)


A call to such a method would contain three arguments: two strings and a character, in that
order. For example:


prepareName(“Herrmann”, “Herman”, ‘G’)


The arguments are copied into the parameter variables one-for-one, in the order listed, as
shown here:


Method Call or Invocation Let’s take a closer look at how we call a method and what happens when


we do so. We’ve already used the printand printlnmethods to display strings on the screen.
Using object-oriented terminology, we sent messages to System.out. Technically, we called
the methods. A method call may or may not have to be appended to an object or class iden-
tifier with a dot in between. (We will explain these different forms of a call statement shortly.)
The arguments to printand printlnwere the strings to be displayed; the method names
were appended to the object identifier System.out.
A call causes control of the computer to jump to the instructions in the method,
which may make use of the argument values that are copied into its parameters. When
the method completes its task, control of the computer returns to the statement follow-
ing the call.


void prepareName(String arg1, String arg1, char arg3)

prepareName(“Herrmann”, “Herman”, ‘G’)
Free download pdf