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:

Rules for creating packages

  1. 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/java directory in Maven-built Java projects.
  2. A package name must be written using lowercase letters and cannot have spaces. This avoids conflicts with class names.
  3. 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.
  4. 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 with org.example. This enables worldwide code sharing and reuse without creating conflicts at class and member levels.

Creating packages

In IntelliJ IDEA IDE, we can follow the below steps to create a package.

  1. Right-click the java directory under src/main/ in the Project tool window.
  2. Select New > Package.
  3. Enter an appropriate package name. For example, org.example.

Things to be mindful of

  1. 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.
  2. 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.