Java Fundamentals  «Prev  Next»

Lesson 3Java Packages
Objective Describe how packages are declared and imported.

The need for packages

You can use a package to group together a related set of classes and interfaces. Packages also provide access protection and namespace management. You can create separate packages to define classes for separate projects, such as Android games and online healthcare systems. Further, you can create subpackages within these packages, such as separate subpackages for GUIs, database access, networking, and so on.
Note: In real-life projects, you will rarely work with a package-less class or interface. Almost all organizations that develop software have strict package naming rules, which are often documented. All classes and interfaces are defined in a package. If you do not include an explicit package statement in a class or an interface, it is part of a default package.

Java Packages

The Java API is organized by packages . Each package contains related classes and interfaces. A package is used to define a separate naming context. Packages allow multiple classes and interfaces to have the same name. Classes and interfaces with the same name are defined in separate packages. Suppose that both you and I want to define a class named MyClass. I can define my class in a package named myPackage and you can define your class in a package named yourPackage.
A package naming convention can help assure that you are creating a unique package name.
The package statement is used to identify the package with which the classes and interfaces of a source code file should be associated. Its syntax is as follows:
package packageName;
If a package statement is included in a source code file, it must appear as the first non-blank, non-comment line in the file. If a source code file does not have a package statement, then the file's classes and interfaces are put in the default (no name) package.

Importing from other packages

All classes and interfaces of the same package can be referenced without having to identify their package name. However, to reference the classes and interfaces of other packages, you either need to prepend their package name, or import them using the import statement. Its syntax takes the following three forms:
import packageName.*;
import packageName.className;
import packageName.interfaceName;

The first form imports all classes and interfaces of the package named packageName. The other forms are used to import specific classes and interfaces.

There is no need to import the java.lang package. Since it contains classes and interfaces that are fundamental to all Java programs, it is always imported by default.

Packages Compilation Units - Quiz

Click the Quiz link below to check your understanding of packages and compilation units.
Packages Compilation Units - Quiz