Sub topic 2
Ambiguous names and how to resolve them
This chapter assumes you understand Java packages, fully qualified names, and single-type and wildcard imports.
Ambiguous names and how to resolve them
An import module declaration makes exported public top-level types available by simple name. If two imported modules export types with the same simple name, using that name is a compile-time error.
import module java.base;
import module java.sql;
import java.util.Date;
public class ResolveNames {
public static void main(String[] args) {
Date utilDate = new Date();
java.sql.Date sqlDate =
new java.sql.Date(utilDate.getTime());
System.out.println(utilDate);
System.out.println(sqlDate);
}
}Both java.base and java.sql make a type named Date available. The explicit single-type import selects java.util.Date, so Date is no longer ambiguous. A fully qualified name, such as java.sql.Date, always identifies the intended type.
A package wildcard import and a module import can also contribute competing names. The compiler does not choose based on declaration order.
Modules reached through `requires transitive`
A module import does not grant access to a module. The source module must already read the imported module.
module com.example.app {
requires java.sql;
}A module can read another module indirectly when an intermediate module declares requires transitive. Module imports can then expose types from modules reached through that readability relationship. The import declaration changes name lookup only; it does not change the module graph or bypass exports.
Shadowing and precedence rules
A declaration in a nearer scope takes precedence over an on-demand import. A local or nested type can therefore hide a type with the same name from an imported module. A single-type import takes precedence over package and module on-demand imports.
If two single-type imports use the same simple name, the conflict cannot be resolved by order. Remove one import or use fully qualified names.
Exercise
Why does java.sql.Date still need qualification when java.util.Date is imported explicitly?
Show answer
The explicit import selects java.util.Date for the simple name Date; it does not rename or hide the distinct java.sql.Date type.