Java Packages and Imports
Context: FIT2099_MOC Β· organise many classes into named folders Β· the namespace layer above a single Java file
Quick Revision
- π― Objective: group related classes into a package (a namespace = a folder) β avoid name clashes and structure a project.
- β‘ Key Constraint: the
packagedeclaration must be the very first statement in the file (before anyimport); the folder path on disk must match the dotted package name.
π Core
- Package β a namespace grouping related classes; declared
package com.smarthome;as the first line. - Folder = package β
com.smarthomeβ the file lives incom/smarthome/; mismatch = wonβt compile. - Import β pull a class from another package into scope:
import java.util.ArrayList;β then useArrayListunqualified. - Order β
packageline βimportlines β class declaration; imports sit between the two. - Fully-qualified name β without an import, refer to a class by its full path:
java.util.ArrayList list = .... - Module β (Java 9+) a collection of packages, one level above packages, described by a
module-info.javamodule descriptor.
π§© Modules (Java 9+)
module-info.javaβ declares the moduleβs name plus its boundary:
module my-module {
requires javafx.controls; // depend on (read) another module
exports my.program.package; // make this package visible to all
exports my.program.package to other-module; // ...or visible to ONE module
provides someInterface with my.program.Implementation; // offer a service
}requiresβ a dependency β my-module reads the required module.exportsβ makes a specific package visible (optionally onlytoa named module); unexported packages stay module-private even ifpublic.provides β¦ with β¦β registers a concrete implementation of a service interface.
β οΈ Common Mistakes
- π‘ Wildcard import
*βimport java.util.*;pulls the whole package β discouraged: hurts readability and risks ambiguous names; import the specific class. - π‘
packagenot first β any code (even animport) before thepackageline is a compile error. - π‘ Path β name β the on-disk directory structure must mirror the dotted package name exactly.
π§ Active Recall
Why is a wildcard import (
import pkg.*;) generally discouraged over naming the class?Answer
- Short answer: it drags every class in the package into scope, hiding exactly what the file depends on and risking name clashes between two packages that both define a
Date(or similar).- Why: Explicit dependencies β a specific import documents the real coupling and lets the compiler resolve names unambiguously.