Java Reference
In-Depth Information
3.1 Parameters
Humans are very good at learning new tasks. When we learn, we often develop a single
generalized solution for a family of related tasks. For example, someone might ask
you to take 10 steps forward or 20 steps forward. These are different tasks, but they
both involve taking a certain number of steps forward. We think of this action as a
single task of taking steps forward, and we understand that the number of steps will
vary from one task to another. In programming terms, we refer to the number of steps
as a parameter that allows us to generalize the task.
Parameter (Parameterize)
Any of a set of characteristics that distinguish different members of a family
of tasks. To parameterize a task is to identify a set of its parameters.
For a programming example, let's return to the DrawFigure2 program of Chapter 2.
It performs its task adequately, but there are several aspects of this program that we
can improve. For example, there are many different places where a for loop writes
out spaces. This approach is redundant and can be consolidated into a single method
that performs all space-writing tasks.
Each space-writing task requires a different number of spaces, so you need some
way to tell the method how many spaces to write. The methods you've written so far
have a simple calling mechanism where you say:
writeSpaces();
One approach might be to set a variable to a particular value before the method is
called:
int number = 10;
writeSpaces();
Then the method could look at the value of the variable number to see how many
spaces to write. Unfortunately, this approach won't work. Recall from Chapter 2 that
scope rules determine where variables can be accessed. Following those rules, the
variable number would be a local variable in main that could not be seen inside
writeSpaces .
Instead, you can specify one or more parameters to a method. The idea is that
instead of writing a method that performs just one version of a task, you write a more
flexible version that solves a family of related tasks that all differ by one or more
parameters. In the case of the writeSpaces method, the parameter is the number of
spaces to write.
The following is the definition of writeSpaces with a parameter for the number
of spaces to write:
 
Search WWH ::




Custom Search