Java Reference
In-Depth Information
If you ever are in a situation where you need to use two classes with the same name but
in different packages, then using imports does not work. You will need to refer to each class
by their fully qualifi ed name in your source fi le. The following code compiles successfully:
1. public class FullyQualifiedDemo {
2. public javax.management.AttributeList a1;
3. public javax.swing.text.html.parser.AttributeList a2;
4. }
The FullyQualifiedDemo program demonstrates why packages are often referred to as
namespaces because package names are used to avoid naming confl icts. Without packages,
there is no way for the compiler or the JVM to distinguish between the two AttributeList
classes. However, because the two AttributeList classes are declared in different
packages, they can be referred to by their fully qualifi ed names to avoid any ambiguity.
Naming Convention for Packages
The namespace ambiguity situation can still occur if programmers happen to use the
same package names in different programs. If you and I both write a class called Dog and
we both defi ne Dog in a package named pets , then a naming confl ict still occurs. How-
ever, the standard Java naming convention for a package name is to use your company's
domain name (in reverse) as a prefi x to your package names. For example, a class written
by an employee of Sybex uses a package name that starts with com.sybex .
Subsequent components of the package name may include your department and project
name, followed by a descriptive name for the package. For example, com.sybex
.scjpbook.pets is a good package name for a class named Dog that appears in this topic.
It is extremely unlikely that someone else would use this package name, although I am
sure there are other Dog classes in the world.
If everyone who writes Java code follows this naming convention for package names,
then naming confl icts can only occur within a single company or project, making it easier
to resolve the naming confl ict.
Package Directory Structure
The exam objectives state that “given the fully-qualifi ed name of a class that is deployed
inside and/or outside a JAR fi le,” you need to be able to “construct the appropriate
directory structure for that class.” This objective refers to the required directory structure
that results from using packages. In addition to creating a namespace, packages organize
your programs by grouping related classes and interfaces together. One result of using
packages is that the bytecode of a class or interface must appear in a directory structure
that matches its package name. If you do not put your bytecode in the proper directory
structure, the compiler or the JVM will be unable to fi nd your classes.
Search WWH ::




Custom Search