Java Reference
In-Depth Information
variable, just as fields are, so they are also used to hold data. Parameters are variables that
are defined in the header of a constructor or method:
public TicketMachine(int cost)
This constructor has a single parameter, cost , which is of type int —the same type as the
price field it will be used to set. A parameter is used as a sort of temporary messenger, car-
rying data originating from outside the constructor or method and making it available inside it.
Figure 2.4 illustrates how values are passed via parameters. In this case, a BlueJ user enters
the external value into the dialog box when creating a new ticket machine (shown on the left),
and that value is then copied into the cost parameter of the new machine's constructor. This
is illustrated with the arrow labeled (A). The box in the TicketMachine object in Figure 2.4,
labeled “TicketMachine (constructor),” represents additional space for the object that is cre-
ated only when the constructor executes. We shall call it the constructor space of the object (or
method space when we talk about methods instead of constructors, as the situation there is the
same). The constructor space is used to provide space to store the values for the constructor's
parameters. In our diagrams, all variables are represented by white boxes.
Concept:
The scope of a
variable defines the
section of source
code from which
the variable can be
accessed.
We distinguish between the parameter names inside a constructor or method and the parameter
values outside by referring to the names as formal parameters and the values as actual parame-
ters. So cost is a formal parameter, and a user-supplied value such as 500 is an actual parameter.
A formal parameter is available to an object only within the body of a constructor or method
that declares it. We say that the scope of a parameter is restricted to the body of the construc-
tor or method in which it is declared. In contrast, the scope of a field is the whole of the class
definition - it can be accessed from anywhere in the same class. This is a very important dif-
ference between these two sorts of variables.
Concept:
The lifetime of a
variable describes
how long the vari-
able continues to
exist before it is
destroyed.
A concept related to variable scope is variable lifetime. The lifetime of a parameter is limited to
a single call of a constructor or method. When a constructor or method is called, the extra space
Figure 2.4
Parameter passing (A)
and assignment (B)
WLFNHW0D
7LFNHW0DFKLQH
SULFH
EDODQFH
WRWDO
%
7LFNHW0DFKLQH
FRQVWUXFWRU
$
WLFNHW&RVW
 
Search WWH ::




Custom Search