News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

Java Tutorial – 15 – Packages and Import

Packages are used to avoid naming conflicts and to organize code files into different directories. So far in this tutorial the code file has been located at the root of the project’s source directory. Therefore, it has belonged to the so called default package. In Java, the directory a file belongs to, relative to the project’s source directory, corresponds to the package name.

To assign a code file to a package, for example “mypackage”, it must be moved to a folder by that name, under the project directory. Furthermore, the file must specify which package it belongs to by using the package keyword followed by the package name (and path). There may only be one package statement in each source file and it must be the first line of code, except for any comments. Note that the naming convention for packages is all lowercase.

package mypackage; // this file belongs to mypackage

Packages may be any number of directory levels deep and the levels in the hierarchy are separated by dots. For example, if the “mypackage” folder containing the code file is placed in a project folder called “sub”, the package declaration would need to look like this:

package sub.mypackage;

Say this file contains a public class called MyClass. To access MyClass from another source file there are two options. The first is to type the fully qualified name.

mypackage.sub.MyClass m;

Import specific class

The second option is to shorten the fully qualified name by including the class with the import keyword. An import statement must be located before all other members in the code file, and it has no other purpose than to free the programmer from having to type the fully qualified name.

import mypackage.sub.MyClass;
// …
MyClass m;

Import package

In addition to importing a specific class, all types inside of a package can be imported by using an asterisk (*). Note that this does not import any of the subpackages.

import java.util.*;

Import static

A third variation of the import statement is the static import, which imports all static members of a class. Once the static members are imported, they can be used without having to specify the class name.

import static java.lang.Math.*;
// …
double pi = PI; // Math.PI
Recommended additional reading:
Sams - Teach Yourself Java in 24 Hours