Home > Articles

Language Fundamentals

  • Print
  • + Share This
This chapter is from the book

Identifying Packages

Java classes and interfaces are organized into packages. Packages are used to group classes and interfaces that implement a specific API or part of an API. Packages provide a naming context for classes and interfaces. In other words, packages enable different programmers (or even the same programmer) to create classes and interfaces with the same name. For example, if you and I both create a class named Cool and then use the two different versions of Cool in the same program, the compiler and runtime system won't know which version to use. However, if I put my Cool class in the My package, and you put your Cool class in the You package, the compiler and runtime system will have no problem, as long as we refer to Cool using its package name.

Use of Packages

In addition to being used as a naming context, packages are used to organize related classes and interfaces into a single API unit to which access can be controlled.

A package statement identifies packages. A package statement must appear as the first statement in a source code file:

package packageName;

If a package statement is omitted, the classes and interfaces declared within the package are put into the default no-name package. The package name and the CLASSPATH environment variable are used to find classes and interfaces during compilation and execution.

Importing Classes and Interfaces

The fact that you import all of the classes and interfaces of a package does not mean that they will be loaded into your program. Importing a class or interface just means that it can be referenced from your program. You can also reference a class (or interface) using its fully qualified name (that is, packageName.className) without having to import it.

  • + Share This
  • 🔖 Save To Your Account