Module Accessibility in Java

Module accessibility in Java is a crucial concept that governs the conditions under which a type in one module can be accessed by another module. This mechanism ensures that only the intended parts of a module are exposed to other modules, thereby enhancing encapsulation and modularity in Java applications.

Overview of Module Accessibility

Module accessibility is determined by several factors:

  1. Public Type: The type must be declared as public.
  2. Exported Package: The type must belong to a package that the module exports.
  3. Module Reading: The accessing module must read the module containing the type.

These conditions ensure that a type is only accessible if it is explicitly made available by the module's author, providing a controlled way to expose module internals.

Controlling Access with Exports

In Java, module accessibility is managed through the exports directive. This directive can be further refined by using qualified exports, which restrict access to specific modules. For example, the exports directive can be followed by to ${modules}, where ${modules} is a comma-separated list of module names. This allows only the specified modules to access the package, while others are denied access.

Example of Module Accessibility

Consider a scenario where a type Drink in a module bar needs to be accessed by code in a module customer. For this to happen, the following conditions must be met:

  • Drink must be a public type.
  • Drink must belong to a package that bar exports.
  • The customer module must read the bar module.

This example illustrates how module accessibility rules are applied to control access between modules.

Visual Representation

To better understand module accessibility, consider the following figure:

Figure 3.7 The module bar contains a public type Drink (1) in an exported package (2). The module customer reads the module bar (3), so all requirements are fulfilled for code in customer to access Drink. Figure 3.7 The module bar contains a public type Drink (1) in an exported package (2). The module customer reads the module bar (3), so all requirements are fulfilled for code in customer to access Drink.

This figure illustrates a practical example where all the requirements for module accessibility are fulfilled, allowing the customer module to access the Drink type in the bar module.

FAQ (Frequently asked questions)