Sub topic 3
Static Imports and Packaged Java Code
Assume you can write a class with a main method, compile it, and use basic access modifiers. This chapter focuses on how imports and package boundaries affect larger programs.
Static imports
A static import lets you use a static field or method without repeating its class name. Import only the members that improve readability.
import static java.lang.Math.max;
import static java.lang.Math.PI;
public class StaticImportDemo {
public static void main(String[] args) {
System.out.println(max(3, 7));
System.out.println(PI);
}
}Without static imports, the calls would be Math.max(3, 7) and Math.PI. Wildcard static imports, such as import static java.lang.Math.*;, are legal but can make the source harder to understand when names collide.
Package-private and protected access
A member with no access modifier is package-private. Classes in the same package can use it, but classes in other packages cannot. protected also permits access from the same package. A subclass in another package may access a protected member through inheritance, subject to Java's access rules.
package com.example.shop.model;
class PriceFormatter {
static String format(double price) {
return String.format("%.2f", price);
}
}PriceFormatter cannot be imported by a class in another package because the class itself is package-private. Use package-private access for implementation details shared by closely related classes.
Compiling and running packaged code
Place source files in directories matching their packages. The -d option tells javac where to create class files.
javac -d out src/com/example/shop/Main.java src/com/example/shop/model/Product.java
java -cp out com.example.shop.MainThe classpath contains locations where Java searches for compiled classes. Run a packaged class by its fully qualified name, including its package.
Why to avoid the default package
A class without a package declaration is in the default, or unnamed, package. It is difficult to organize, and named packages cannot reliably import its classes. Use a named package in real projects.
JAR files and modules
A JAR bundles compiled classes and resources into one distributable file. A module adds stronger structure: it declares which packages it exports and which modules it requires. Use packages for namespaces and access organization; use modules when an application or library needs explicit dependency and API boundaries.
Exercise
How do you run com.example.shop.Main when its class files are under out?
Show answer
Run java -cp out com.example.shop.Main.