Java Reference
In-Depth Information
We encountered the import statement for the first time in Chapter 4. Now is the time to look at
it a little more closely.
Java classes that are stored in the class library are not automatically available for use, like the
other classes in the current project. Rather, we must state in our source code that we would like
to use a class from the library. This is called importing the class and is done using the import
statement. The import statement has the form
import qualified-class-name ;
Because the Java library contains several thousand classes, some structure is needed in the
organization of the library to make it easier to deal with the large number of classes. Java uses
packages to arrange library classes into groups that belong together. Packages can be nested
(that is, packages can contain other packages).
The classes ArrayList and Random are both in the package java.util . This information can
be found in the class documentation. The full name or qualified name of a class is the name of
its package, followed by a dot followed by the class name. Thus, the qualified names of the two
classes we used here are java.util.ArrayList and java.util.Random .
Java also allows us to import complete packages with statements of the form
import package-name .*;
So the following statement would import all class names from the java.util package:
import java.util.*;
Listing all used classes separately, as in our first version, is a little more work in terms of typing
but serves well as a piece of documentation. It clearly indicates which classes are actually used
by our class. Therefore, in this topic, we shall tend to use the style of the first example, listing
all imported classes separately.
There is one exception to these rules: some classes are used so frequently that almost every
class would import them. These classes have been placed in the package java.lang , and this
package is automatically imported into every class. So we do not need to write import state-
ments for classes in java.lang . The class String is an example of such a class.
Exercise 5.21 Implement in your version of the tech-support system the random-response
solution discussed here.
Exercise 5.22 What happens when you add more (or fewer) possible responses to the
responses list? Will the selection of a random response still work properly? Why or why not?
The solution discussed here is also in the topic projects under the name tech-support2. We
recommend, however, that you implement it yourself as an extension of the base version.
5.6
Using maps for associations
We now have a solution to our technical-support system that generates random responses. This
is better than our first version, but is still not very convincing. In particular, the input of the user
does not influence the response in any way. It is this area that we now want to improve.
 
 
Search WWH ::




Custom Search