System, but they may not be reproduced for publication



Yüklə 83 Mb.
Pdf görüntüsü
səhifə23/82
tarix19.04.2023
ölçüsü83 Mb.
#106251
1   ...   19   20   21   22   23   24   25   26   ...   82
Java A Beginner’s Guide, Eighth Edition ( PDFDrive )


part of Java programming.
Methods return a value to the calling routine using this form of return:
return value;
Here, value is the value returned. This form of return can be used only with methods
that have a non­void return type. Furthermore, a non­void method must return a
value by using this form of return.
You can use a return value to improve the implementation of range( ). Instead of
displaying the range, a better approach is to have range( ) compute the range and
return this value. Among the advantages to this approach is that you can use the value
for other calculations. The following example modifies range( ) to return the range
rather than displaying it.


The output is shown here:
In the program, notice that when range( ) is called, it is put on the right side of an
assignment 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 returned 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 receives 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.
Therefore, isEven( ) has a return type of boolean.


Here is the output produced by the program:
In the program, isEven( ) is called three times, and each time a different value is
passed. Let’s look at this process closely. First, notice how isEven( ) is called. The
argument is specified between the parentheses. When isEven( ) is called the first time,
it is passed the value 10. Thus, when isEven( ) begins executing, the parameter x
receives the value 10. In the second call, 9 is the argument, and x, then, has the value 9.
In the third call, the argument is 8, which is the value that x receives. The point is that
the value passed as an argument when isEven( ) is called is the value received by its
parameter, x.
A method can have more than one parameter. Simply declare each parameter,
separating one from the next with a comma. For example, the Factor class defines a
method called isFactor( ) that determines whether the first parameter is a factor of
the second.


Notice that when isFactor( ) is called, the arguments are also separated by commas.
When using multiple parameters, each parameter specifies its own type, which can
differ from the others. For example, this is perfectly valid:
Adding a Parameterized Method to Vehicle
You can use a parameterized method to add a new feature to the Vehicle class: the
ability to compute the amount of fuel needed for a given distance. This new method is
called fuelneeded( ). This method takes the number of miles that you want to drive
and returns the number of gallons of gas required. The fuelneeded( ) method is
defined like this:
Notice that this method returns a value of type double. This is useful since the amount
of fuel needed for a given distance might not be a whole number. The entire Vehicle
class that includes fuelneeded( ) is shown here:


The output from the program is shown here:


Try This 4­1
Creating a Help Class
If one were to try to summarize the essence of the class in one sentence, it might be
this: a class encapsulates functionality. Of course, sometimes the trick is knowing
where one “functionality” ends and another begins. As a general rule, you will want
your classes to be the building blocks of your larger application. In order to do this,
each class must represent a single functional unit that performs clearly delineated
actions. Thus, you will want your classes to be as small as possible—but no smaller!
That is, classes that contain extraneous functionality confuse and destructure code, but
classes that contain too little functionality are fragmented. What is the balance? It is at
this point that the science of programming becomes the art of programming.
Fortunately, most programmers find that this balancing act becomes easier with
experience.
To begin to gain that experience you will convert the help system from 
Try This 3­3
in
the preceding chapter into a Help class. Let’s examine why this is a good idea. First, the
help system defines one logical unit. It simply displays the syntax for Java’s control
statements. Thus, its functionality is compact and well defined. Second, putting help in
a class is an esthetically pleasing approach. Whenever you want to offer the help
system to a user, simply instantiate a help­system object. Finally, because help is
encapsulated, it can be upgraded or changed without causing unwanted side effects in
the programs that use it.
1. Create a new file called HelpClassDemo.java. To save you some typing, you might
want to copy the file from 
Try This 3­3
, Help3.java, into HelpClassDemo.java.
2. To convert the help system into a class, you must first determine precisely what
constitutes the help system. For example, in Help3.java, there is code to display a
menu, input the user’s choice, check for a valid response, and display information
about the item selected. The program also loops until the letter q is pressed. If you
think about it, it is clear that the menu, the check for a valid response, and the display
of the information are integral to the help system. How user input is obtained, and
whether repeated requests should be processed, are not. Thus, you will create a class
that displays the help information, the help menu, and checks for a valid selection. Its
methods will be called helpOn( ), showMenu( ), and isValid( ), respectively.
3. Create the helpOn( ) method as shown here:


4. Next, create the showMenu( ) method:


5. Create the isValid( ) method, shown here:
6. Assemble the foregoing methods into the Help class, shown here:


7. Finally, rewrite the main( ) method from 
Try This 3­3
so that it uses the new Help
class. Call this class HelpClassDemo. The entire listing for HelpClassDemo.java is
shown here:



When you try the program, you will find that it is functionally the same as before. The
advantage to this approach is that you now have a help system component that can be


reused whenever it is needed.
CONSTRUCTORS
In the preceding examples, the instance variables of each Vehicle object had to be set
manually using a sequence of statements, such as:
An approach like this would never be used in professionally written Java code. Aside
from being error prone (you might forget to set one of the fields), there is simply a
better way to accomplish this task: the constructor.
constructor initializes an object when it is created. It has the same name as its class
and is syntactically similar to a method. However, constructors have no explicit return
type. Typically, you will use a constructor to give initial values to the instance variables
defined by the class, or to perform any other startup procedures required to create a
fully formed object.
All classes have constructors, whether you define one or not, because Java
automatically provides a default constructor. In this case, non­initialized member
variables have their default values, which are zero, null, and false, for numeric types,
reference types, and booleans, respectively. Once you define your own constructor, the
default constructor is no longer used.
Here is a simple example that uses a constructor:


In this example, the constructor for MyClass is
This constructor assigns the instance variable x of MyClass the value 10. This
constructor is called by new when an object is created. For example, in the line
the constructor MyClass( ) is called on the t1 object, giving t1.x the value 10. The
same is true for t2. After construction, t2.x has the value 10. Thus, the output from the
program is
PARAMETERIZED CONSTRUCTORS
In the preceding example, a parameter­less constructor was used. Although this is fine
for some situations, most often you will need a constructor that accepts one or more
parameters. Parameters are added to a constructor in the same way that they are added
to a method: just declare them inside the parentheses after the constructor’s name. For


example, here, MyClass is given a parameterized constructor:
The output from this program is shown here:
In this version of the program, the MyClass( ) constructor defines one parameter
called i, which is used to initialize the instance variable, x. Thus, when the line
executes, the value 10 is passed to i, which is then assigned to x.
ADDING A CONSTRUCTOR TO THE VEHICLE
CLASS
We can improve the Vehicle class by adding a constructor that automatically initializes
the passengers, fuelcap, and mpg fields when an object is constructed. Pay special
attention to how Vehicle objects are created.


Both minivan and sportscar are initialized by the Vehicle( ) constructor when they
are created. Each object is initialized as specified in the parameters to its constructor.
For example, in the following line,
the values 7, 16, and 21 are passed to the Vehicle( ) constructor when new creates the


object. Thus, minivan’s copy of passengers, fuelcap, and mpg will contain the
values 7, 16, and 21, respectively. The output from this program is the same as the
previous version.
THE NEW OPERATOR REVISITED
Now that you know more about classes and their constructors, let’s take a closer look at
the new operator. In the context of an assignment, the new operator has this general
form:

Yüklə 83 Mb.

Dostları ilə paylaş:
1   ...   19   20   21   22   23   24   25   26   ...   82




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©genderi.org 2024
rəhbərliyinə müraciət

    Ana səhifə