A package is a unique namespace that can contain a combination of top-level classes, other top-level types, and subpackages. Only types that are declared public can be accessed from outside the package. Furthermore, the constants, constructors, methods, and nested types that describe a class's interface must be declared public to be accessible from beyond the package.
Every package has a name, which must be a nonreserved identifier. The member access operator separates a package name from a subpackage name, and separates a package or subpackage name from a type name. For example, the two member access operators in graphics.shapes.Circle separate package name graphics from the shapes subpackage name, and separate subpackage name shapes from the Circle type name.
NOTE: Each of Java SE's standard class library and Android's class library organizes its many classes and other top-level types into multiple packages. Many of these packages are subpackages of the standard java package. Examples include java.io (types related to input/output operations), java.lang (language-oriented types), java.lang.reflect (reflection-oriented language types), java.net (network-oriented types), and java.util (utility types).
Suppose you have two different graphics.shapes packages, and suppose that each shapes subpackage contains a Circle class with a different interface. When the compiler encounters System.out.println( new Circle(10.0, 20.0, 30.0).area()); in the source code, it needs to verify that the area() method exists.
The compiler will search all accessible packages until it finds a graphics.shapes package that contains a Circle class. If the found package contains the appropriate Circle class with an area() method, everything is fine. Otherwise, if the Circle class does not have an area() method, the compiler will report an error.
This scenario illustrates the importance of choosing unique package names. Specifically, the top-level package name must be unique. The convention in choosing this name is to take your Internet domain name and reverse it. For example, I would choose ca.mb.javajeff as my top-level package name because javajeff.mb.ca is my domain name. I would then specify ca.mb.javajeff.graphics.shapes.Circle to access Circle.
NOTE: Reversed Internet domain names are not always valid package names. One or more of its component names might start with a digit (6.com), contain a hyphen (-) or other illegal character (aq-x.com), or be one of Java's reserved words (int.com). Convention dictates that you prefix the digit with an underscore (com._6), replace the illegal character with an underscore (com.aq_x), and suffix the reserved word with an underscore (com.int_).
Was this article helpful?