Java Reference
In-Depth Information
The keyword import is followed by the specification of what you want to import. The wildcard * ,
following the period after the package name, selects all the classes in the package, rather like selecting
all the files in a directory. Now you can refer to any public class in the package just by using the class
name. Again, the names of other classes in your program must be different from the names of the
classes in the package.
If you want to add a particular class rather than an entire package, you specify its name explicitly in the
import statement:
import Geometry.Shapes3D.Sphere; // Include the class Sphere
This includes only the Sphere class into the source file. By using a separate import statement for each
individual class from the package, you can ensure that your source file only includes the classes that you
need. This reduces the likelihood of name conflicts with your own classes, particularly if you are not
fully familiar with the contents of the package and it contains a large number of classes.
Note that the * can only be used to select all the classes in a package. You can't use
Geometry.* to select all the packages in the directory Geometry .
Packages and Names in Your Programs
A package creates a self-contained environment for naming your classes. This is the primary reason for
having packages in Java. You can specify the names for classes in one package without worrying about
whether the same names have been used elsewhere. Java makes this possible by treating the package
name as part of the class name - actually as a prefix. This means that the class Sphere in the package
Geometry.Shapes3D has the full name Geometry.Shapes3D.Sphere . If you don't use an import
statement to incorporate the class in your program, you can still make use of the class by referring to it
using its full class name. If you needed to do this with the class Sphere , you might declare a variable
with the statement:
Geometry.Shapes3D.Sphere ball = new Geometry.Shapes3D.Sphere(10.0, 1.0, 1.0, 1.0);
While this is rather verbose, and certainly doesn't help the readability of the program, it does ensure there
will be no conflict between this class and any other Sphere class that might be part of your program. You
can usually contrive that your class names do not conflict with those in the commonly used standard Java
packages, but in cases where you can't manage this, you can always fall back on using fully qualified class
names. Indeed, there are occasions when you have to do this. This is necessary when you are using two
different classes from different packages that share the same basic class name.
Search WWH ::




Custom Search