Sub topic 1
Java Module Import Declarations: Importing Whole Modules with `import module`
Prerequisites
Assume you can write and compile Java classes, use single-type imports such as import java.util.List;, and use on-demand imports such as import java.util.*;. You should also know that a fully qualified name includes its package, such as java.util.List.
Recap: Single-Type and On-Demand Imports
A single-type import makes one type available by its simple name:
import java.util.ArrayList;An on-demand import uses * to make types from one package available:
import java.util.*;The wildcard does not recursively include subpackages. For example, java.util.* does not import types from java.util.concurrent.
Recap: Modules, Exports and Readability
A module is a named group of packages. Its exports declarations control which packages other modules may use. A module can read another module when its module graph allows access, usually through requires.
An import declaration does not bypass these rules. It can name only types that are accessible from the source file.
The `import module` Declaration
Java provides a module import declaration:
import module java.base;This lets the source use accessible public types exported by java.base without listing each package. For example:
import module java.base;
public class ModuleImportDemo {
public static void main(String[] args) {
List<String> names = List.of("Ada", "Grace");
System.out.println(names);
}
}The declaration is different from import java.*;. It refers to a module, not a package.
What Exactly Gets Imported
A module import makes the public top-level types from the module's exported packages available by simple name. It does not import:
- Non-exported packages
- Non-public types
- Types from unrelated modules
- Members of a type
- Subpackages as a separate wildcard operation
If two imported modules expose the same simple name, using that name becomes ambiguous. Use a single-type import or a fully qualified name to resolve the clash.
Exercise
What does import module java.base; make available?
Show answer
It makes accessible public top-level types from packages exported by java.base available by simple name.