Java Reference
In-Depth Information
from the roll method is ignored in several calls, while in others the return value
is used in a calculation.
Constructors do not have a return type (not even void ) and therefore cannot
return a value. We discuss constructors in more detail later in this chapter.
Parameters
As we defined in Chapter 2, a parameter is a value that is passed into a method
when it is invoked. The parameter list in the header of a method specifies the types
of the values that are passed and the names by which the called method will refer
to those values.
The names of the parameters in the header of the method declaration are called
formal parameters. In an invocation, the values passed into a method are called
actual parameters. The actual parameters are also called the
arguments to the
method.
A method invocation and definition always give the parameter list in parenthe-
ses after the method name. If there are no parameters, an empty set of parentheses
is used, as is the case in the roll and getFaceValue methods. The Die constructor
also takes no parameters, although constructors often do.
The formal parameters are identifiers that serve as variables inside
the method and whose initial values come from the actual parameters
in the invocation. When a method is called, the value in each actual
parameter is copied and stored in the corresponding formal param-
eter. Actual parameters can be literals, variables, or full expressions. If
an expression is used as an actual parameter, it is fully evaluated before the method
call and the result is passed as the parameter.
KEY CONCEPT
When a method is called, the actual
parameters are copied into the
formal parameters.
The only method in the Die class that accepts any parameters is the setFaceValue
method, which accepts a single int parameter. The formal parameter name is value .
In the main method, the value of 4 is passed into it as the actual parameter.
The parameter lists in the invocation and the method declaration must match
up. That is, the value of the first actual parameter is copied into the first formal
parameter, the second actual parameter into the second formal parameter, and so
on, as shown in Figure 4.8. The types of the actual parameters must be consistent
with the specified types of the formal parameters.
Other details regarding parameter passing are discussed in Chapter 7.
Local Data
As we described earlier in this chapter, the scope of a variable or constant is the part
of a program in which a valid reference to that variable can be made. A variable
 
Search WWH ::




Custom Search