Java Packages
Java Packages
Java packages are a mechanism to group Java classes that are related to each other, into the same "module" (package).
A Java package structure is like a directory structure. Its a tree of packages, subpackages and classes inside these classes. In fact, Java packages are indeed organized as directories on your hard drive, or as directories inside a zip file.
At the top you see a directory called "src". This is the source root. It is not a package itself. Inside this directory, all subdirectories are packages. Thus, "collections", "com", "concurrency" etc. are all packages. The packages are illustrated with a folder icon, in the diagram above.
I have expanded two of the sublevel packages, so you can see the classes inside. The classes are illustrated using a little blue circle with a C inside, in the diagram above.
The full path of some subpackage is its name, with all parent packages in front of it, separated by dots. For instance, the full path of "navigation" subpackage is:
com.jenkov.navigation
Similarly, the fully qualified name of a Java class includes its package name. For instance, the full qualified name of the "Page" class, is:
com.jenkov.navigation.Page
Putting Classes into Packages
In order to put your Java classes into packages, you must do two things:
- Put the Java class inside a directory matching the package you want to put the class in.
- Declare that class as part of the package.
Putting the Java classes inside a directory structure that matches the package structure, is pretty straightforward. Just create a source root directory, and inside that, create directories for each package and subpackage recursively. Put the class files into the directory matching the package you want to put it in.
When you have put your class file into the correct directory (matching the package the class should belong to), you have to declare inside that class file, that it belongs to that package. Here is how you do that:
package com.jenkov.navigation; public class Page { ... }
The first line in the code above (in bold) is what declares the class
Page
as belonging to the packagecom.jenkov.navigation
.Package Naming Conventions
Java packages are always written in lowercase letters. Not like Java classes, where the first letter is usually a capital letter.
0 comments: