Java Objects and Classes Package Creation
Learning objective: By the end of this lesson, students will be able to create packages that follow best practices.
Packages in Java
In Java, a package is a way to organize your classes. Packages are needed to:
- Logically group and organize our classes in a tree-like structure.
- Control access to classes and their members.
- Avoid naming conflicts.
- Reuse code by reusing classes in other projects.
Rules for creating packages
- Packages must be created in the src directory or one of its sub-directories. This directory must contain all of the project’s source code.
- Since we use Maven as our build system, some structural rules imposed by it. Accordingly, packages must be created only under the
src/main/javadirectory in Maven-built Java projects.
- Since we use Maven as our build system, some structural rules imposed by it. Accordingly, packages must be created only under the
- A package name must be written using lowercase letters and cannot have spaces. This avoids conflicts with class names.
- Different levels of hierarchies in packages must be separated with a
..- For example,
org.example.app. In the file system, each hierarchical level represents a directory.
- For example,
- Package names must follow the reverse domain notation.
- For example, if an organization’s internet domain address is
example.org, the names of packages developed by this organization must start withorg.example. This enables worldwide code sharing and reuse without creating conflicts at class and member levels.
- For example, if an organization’s internet domain address is
Creating packages
In IntelliJ IDEA IDE, we can follow the below steps to create a package.
- Right-click the
javadirectory undersrc/main/in the Project tool window. - Select
New>Package. - Enter an appropriate package name. For example,
org.example.
Things to be mindful of
- Package names should represent a logical hierarchy. Typically, packages are used to group related classes and interfaces for better organization and maintainability.
- Example of a good package name:
com.mycompany.projectname.modulename.com: Top-level domain or organization (‘com’ stands for commercial, ‘org’ stands for organization, etc.)mycompany: Specific organization or company name.projectname: A specific project within the organization.modulename: A specific module or sub-component within the project.
- Example of a good package name:
- While designing a project, keep in mind that packages enforce the encapsulation of classes. We can access a class from another package only when the class’s access modifier specifically declares it as
public. If classes inside a package are declared without any access modifiers, they are considered package private by default - meaning they can be accessed only by classes within the same package.