Sub topic 2
Fully Qualified Names
Assume you can write and run a Java class with a main method and understand basic classes, methods, and fields.
Fully qualified names
A fully qualified name (FQN) identifies a class with its package and class name:
com.example.shop.model.ProductThe package is com.example.shop.model. The class is Product. Java uses the FQN when it must identify one exact type.
flowchart TD
P["package com.example.shop.model"] --> F["com.example.shop.model.Product"]
F --> I["import com.example.shop.model.Product"]
I --> S["Product"]A package declaration must appear before the class declaration:
package com.example.shop.model;
public class Product {
}Code in another package can use the FQN directly:
com.example.shop.model.Product product =
new com.example.shop.model.Product();This is precise but repetitive.
Importing a single class
A single-type import gives a class a shorter name in one source file:
import com.example.shop.model.Product;
Product product = new Product();The import does not copy the class or change its package. It only lets the compiler resolve Product to its FQN.
What `java.lang` gives you for free
Every Java source file implicitly imports the public types in java.lang. You can therefore use String, System, Math, and Object without writing imports.
public class ImportDemo {
public static void main(String[] args) {
String message = "Largest value: " + Math.max(3, 7);
System.out.println(message);
}
}Wildcard imports and their trade-offs
An on-demand, or wildcard, import makes types in one package available by simple name:
import java.util.*;It does not import subpackages, and it does not import static members. Single-type imports make dependencies more visible, so many teams prefer them. Wildcard imports can be convenient when using many types from the same package.
Resolving name conflicts
Two packages can contain classes with the same simple name. Import one class, then use the other class's FQN:
import java.util.Date;
public class DateConflict {
public static void main(String[] args) {
Date utilDate = new Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println(utilDate.getTime() == sqlDate.getTime());
}
}Java does not allow two single-type imports with the same simple name. Use a fully qualified name whenever an import would be ambiguous.
Exercise
How can code use java.sql.Date when java.util.Date is already imported?
Show answer
Refer to java.sql.Date by its fully qualified name.