Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
Now,square( )will return the square of whatever value it is called with. That is,square( )is
now a general-purpose method that can compute the square of any integer value, rather than
just 10.
Here is an example:

int x, y;
x = square(5); // x equals 25
x = square(9); // x equals 81
y = 2;
x = square(y); // x equals 4

In the first call tosquare( ), the value 5 will be passed into parameteri. In the second call,i
will receive the value 9. The third invocation passes the value ofy, which is 2 in this example.
As these examples show,square( )is able to return the square of whatever data it is passed.
It is important to keep the two termsparameterandargumentstraight. Aparameteris a
variable defined by a method that receives a value when the method is called. For example,
insquare( ),iis a parameter. Anargumentis a value that is passed to a method when it is
invoked. For example,square(100)passes 100 as an argument. Insidesquare( ), the parameteri
receives that value.
You can use a parameterized method to improve theBoxclass. In the preceding examples,
the dimensions of each box had to be set separately by use of a sequence of statements, such as:

mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;

While this code works, it is troubling for two reasons. First, it is clumsy and error prone. For
example, it would be easy to forget to set a dimension. Second, in well-designed Java programs,
instance variables should be accessed only through methods defined by their class. In the
future, you can change the behavior of a method, but you can’t change the behavior of an
exposed instance variable.
Thus, a better approach to setting the dimensions of a box is to create a method that takes
the dimensions of a box in its parameters and sets each instance variable appropriately. This
concept is implemented by the following program:

// This program uses a parameterized method.

class Box {
double width;
double height;
double depth;

// compute and return volume
double volume() {
return width * height * depth;
}

// sets dimensions of box
void setDim(double w, double h, double d) {
width = w;

116 Part I: The Java Language

Free download pdf