J2EEOnline J2EE   





Java Certification  «Prev  Next»
Lesson 3Java Packages
Objective Describe how packages are declared and imported.

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