Java Reference
In-Depth Information
In the program, notice that when range( ) is called, it is put on the right side of an as-
signment statement. On the left is a variable that will receive the value returned by range(
) . Thus, after
executes, the range of the minivan object is stored in range1 .
Notice that range( ) now has a return type of int . This means that it will return an integer
value to the caller. The return type of a method is important because the type of data re-
turned by a method must be compatible with the return type specified by the method. Thus,
if you want a method to return data of type double , its return type must be type double .
Although the preceding program is correct, it is not written as efficiently as it could be.
Specifically, there is no need for the range1 or range2 variables. A call to range( ) can be
used in the println( ) statement directly, as shown here:
In this case, when println( ) is executed, minivan.range( ) is called automatically and its
value will be passed to println( ) . Furthermore, you can use a call to range( ) whenever
the range of a Vehicle object is needed. For example, this statement compares the ranges of
two vehicles:
Using Parameters
It is possible to pass one or more values to a method when the method is called. Recall that
a value passed to a method is called an argument . Inside the method, the variable that re-
ceives the argument is called a parameter . Parameters are declared inside the parentheses
that follow the method's name. The parameter declaration syntax is the same as that used
for variables. A parameter is within the scope of its method, and aside from its special task
of receiving an argument, it acts like any other local variable.
Here is a simple example that uses a parameter. Inside the ChkNum class, the method
isEven( ) returns true if the value that it is passed is even. It returns false otherwise. There-
fore, isEven( ) has a return type of boolean .
Search WWH ::




Custom Search