Java Reference
In-Depth Information
The
import
declaration specifies the packages and classes that will be used in a
program so that the fully qualified name is not necessary with each reference. As
we've seen, the following is an example of an
import
declaration:
import
java.util.Scanner;
This declaration asserts that the
Scanner
class of the
java.util
package may be
used in the program. Once this
import
declaration is made, it is sufficient to use
the simple name
Scanner
when referring to that class in the program.
If two classes from two different packages have the same name,
import
dec-
larations will not suffice because the compiler won't be able to figure out which
class is being referenced in the flow of the code. When such situations arise, which
is rare, the fully qualified names should be used in the code.
Another form of the
import
declaration uses an asterisk (
*
) to indicate that any
class inside the package might be used in the program. Therefore, the following
declaration allows all classes in the
java.util
package to be referenced in the
program without qualifying each reference:
import
java.util.*;
If only one class of a particular package will be used in a program, it is usually
better to name the class specifically in the
import
declaration. However, if two or
more will be used, the
*
notation is usually fine.
The classes of the
java.lang
package are automatically imported
because they are fundamental and can be thought of as basic exten-
sions to the language. Therefore, any class in the
java.lang
package,
such as
System
and
String
, can be used without an explicit
import
declaration. It's as if all program files automatically contain the fol-
lowing declaration:
KEY CONCEPT
All classes of the
java.lang
pack-
age are automatically imported for
every program.
import
java.lang.*;
SELF-REVIEW QUESTIONS
(see answers in Appendix N)
SR 3.10
What is a Java package?
SR 3.11
What does the
java.net
package contain? The
javax.swing
package?
SR 3.12
What package contains the
Scanner
class? The
String
class? The
Random
class? The
Math
class?
SR 3.13
Using the online Java API documentation, describe the
Point
class.
SR 3.14
What does an
import
statement accomplish?
SR 3.15
Why doesn't the
String
class have to be specifically imported into our
programs?
Search WWH ::
Custom Search