Skip to main content

Command Palette

Search for a command to run...

Introduction to Packages and Modules in Java ( Java 9+ )

Published
5 min read
Introduction to Packages and Modules in Java ( Java 9+ )

On Day 14, the focus is on understanding two key concepts in Java: Packages and Modules. These concepts are fundamental to organizing large-scale Java applications, promoting reusability, and controlling the visibility of classes and interfaces across different parts of your code. This article will give a brief but detailed exploration of packages and modules, their purpose, and how to use them effectively.


1. What are Packages in Java?

A package in Java is a namespace that organizes a set of related classes and interfaces. Packages act like directories in a file system and provide a way to group similar types of classes, making large projects more manageable.

Purpose of Packages:

  1. Organization: Packages allow you to group related classes together, improving code structure and readability.

  2. Access Control: By defining classes in different packages, you can control access to class members using access modifiers like public, protected, private, and package-private.

  3. Avoid Name Conflicts: Packages help prevent naming conflicts. Two classes can have the same name as long as they are in different packages.

  4. Reusability: You can import classes from different packages, enhancing code reusability across projects.


2. How to Declare a Package

In Java, you declare a package at the top of your Java file using the package keyword.

Example: Declaring a Package

package com.example.myapp;

public class MyClass {
    public void display() {
        System.out.println("Hello from MyClass in the com.example.myapp package!");
    }
}

In this example:

  • The class MyClass belongs to the package com.example.myapp.

  • The package name follows a reverse domain name convention (e.g., com.example), which helps to avoid name conflicts in large projects.


3. Importing Packages

To use classes from a different package in your program, you need to import the package using the import statement. Java provides two types of imports:

  1. Single Class Import: This imports a specific class.

  2. Wildcard Import: This imports all the classes from a package.

Example: Importing a Class from Another Package

import com.example.myapp.MyClass;

public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.display();  // Output: Hello from MyClass in the com.example.myapp package!
    }
}

Wildcard Import Example:

import com.example.myapp.*;

public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.display();
    }
}
  • Note: Wildcard imports (*) import all classes from the package but do not affect performance.

4. Types of Packages

There are two types of packages in Java:

A. Built-in Packages:

Java provides many built-in packages for common functionalities like file handling, collections, networking, etc.

Examples of built-in packages:

  • java.lang: Automatically imported into every Java program (e.g., String, Math classes).

  • java.util: Contains utility classes like ArrayList, HashMap, etc.

  • java.io: Handles input and output operations (e.g., File, BufferedReader).

B. User-defined Packages:

These are packages created by the user to group related classes and manage the project more effectively. The package names follow the reverse domain naming convention.

Example: Creating a User-defined Package
package com.company.utils;

public class Utility {
    public void printMessage() {
        System.out.println("Utility class in com.company.utils package");
    }
}

5. What are Modules in Java?

Modules were introduced in Java 9 as part of the Java Platform Module System (JPMS) to address the limitations of packages. Modules provide a higher level of organization and control for large applications. While packages group classes, modules group packages, offering even better control over code structure and access.

Purpose of Modules:

  1. Encapsulation: Modules allow encapsulating packages and controlling which parts of the module are exposed to other modules.

  2. Dependency Management: Modules declare their dependencies explicitly. This reduces the risk of classpath hell, where classes conflict or are loaded in the wrong order.

  3. Scalability: Modules help in scaling large Java applications by defining clear boundaries between components.


6. Creating a Module in Java

A module in Java consists of a module descriptor file (module-info.java) and one or more packages. The module-info.java file is located in the root directory of the module and contains declarations of the module's dependencies and the packages it exports.

Example: Defining a Module

module com.example.myapp {
    exports com.example.myapp;    // Exporting a package
    requires java.logging;        // Module dependency
}

In this example:

  • The module com.example.myapp exports the com.example.myapp package.

  • It also declares a dependency on the java.logging module.

Structure of a Module:
com.example.myapp/
 ├── module-info.java
 └── com/example/myapp/
      └── MyClass.java

7. Exporting and Requiring Modules

Modules declare which packages they export and which other modules they require using the exports and requires keywords.

Example: Exporting and Requiring

// module-info.java in module A
module com.moduleA {
    exports com.moduleA.packageA;
}

// module-info.java in module B
module com.moduleB {
    requires com.moduleA;  // Depends on moduleA
}
  • Module A exports the com.moduleA.packageA package.

  • Module B requires com.moduleA to access the exported package.


8. Advantages of Using Modules

  1. Explicit Dependencies: Modules require you to explicitly declare dependencies, making the project easier to understand and maintain.

  2. Better Encapsulation: You can control what parts of the module are accessible to other modules, improving security and modularity.

  3. Enhanced Performance: Modules allow the JVM to load only the required parts of the code, improving application performance and memory efficiency.

  4. Support for Large Projects: Modules help manage larger projects by organizing them into smaller, independent units.


9. Difference Between Packages and Modules

PackagesModules
Group related classes and interfaces.Group related packages.
Do not support explicit dependencies.Explicitly declare dependencies on other modules.
No access control beyond public, protected, and private.Can restrict which packages are exported and imported.
Available since the inception of Java.Introduced in Java 9 with JPMS.

10. Summary

By the end of Day 14, we will have a clear understanding of:

  1. Packages: Their role in organizing and grouping related classes, preventing name conflicts, and promoting reusability.

  2. Modules: How they enhance package functionality by providing explicit dependencies, better encapsulation, and scalability for large applications.

  3. The syntax for creating packages and modules, importing packages, and defining module descriptors.

  4. The advantages of using modules in modern Java development and how they differ from traditional packages.

With this knowledge, you’ll be able to structure your Java projects more efficiently and take advantage of the module system introduced in Java 9 for large-scale applications. Stay tuned! for further updates on Java.

More from this blog

Mohit's blog

51 posts