Week 148 — What are module import declarations and how are they used?
Question of the Week #148
What are module import declarations and how are they used?
6 Replies
When referencing a class from a different package in a Java program, the fully qualified name of that class must either be written out or class must be imported. This is typically done using the
import keyword followed by the fully qualified name of the imported class:
In addition to importing classes, it is also possible to use wildcard imports that include all classes in a package. Wildcard imports are written with a * instead of the class name:
However, this is not the end. It is not just possible to import all classes in a package with a single import statement but it is also possible to do that for an entire (JPMS) module using import module followed by the name of the module to import. For instance, both the java.time and java.util packages are in the java.base module which can be imported using import module java.base;
When using compact source files, the java.base module is imported implicitly so classes within that module don't have to be imported explicitly:
If two types with the same name are imported via module imports, references to it are ambiguous. For example, the packages
java.text, java.lang.annotation and java.lang.classfile (all in the java.base module) contain a type named Annotation.
To still use such types when module imports are used, the developer needs to decide which of these types to use and import the chosen type explicitly:
This can also occur with types from different modules when both modules are imported using an import module statement.
📖 Sample answer from dan1st
Module import declarations are statements that allow for the concise import of an entire module's exported packages and their public classes and interfaces.
Submission from kasinathan2008
I can use module import except import lot of source file
for example
import module java.base;
it will help people import java source except writing import java.util.ArryList; import java.util.List; import java.lang; etc.
what if module have two same name?
java.base and java.sql both have Date type
It is need to add a import statement
import module java.base;
import module java.sql;
import java.sql.Date;
orjava.sql.Data date; instead of Date date;Submission from cotafn_30465
Java code can be organized with: methods, classes, packages and modules. Classes from other packages can be imported like so:
But as the program grows, it can lead to very lengthy import statements which are typically resolved by using wildcards:
Module import is a new Java 25 feature that allows you to import all the packages that a module provides in a single statement.
This was added as a convenience for when you don't want to write verbose import statements, for example: when trying new things.
⭐ Submission from giinko0103