Java Package - Using Packages

Using Packages

In a Java source file, the package that this file's class or classes belong to is specified with the package keyword. This keyword is usually the first keyword in the source file.

package java.awt.event;

To use a package's classes inside a Java source file, it is convenient to import the classes from the package with an import declaration. The following declaration

import java.awt.event.*;

imports all classes from the java.awt.event package, while the next declaration

import java.awt.event.ActionEvent;

imports only the ActionEvent class from the package. After either of these import declarations, the ActionEvent class can be referenced using its simple class name:

ActionEvent myEvent = new ActionEvent;

Classes can also be used directly without an import declaration by using the fully qualified name of the class. For example,

java.awt.event.ActionEvent myEvent = new java.awt.event.ActionEvent;

does not require a preceding import declaration.

Note that if you do not use a package declaration, your class ends up in an unnamed package. Classes in an unnamed package cannot be imported from classes in any other package.

Read more about this topic:  Java Package