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 package declaration must be the very first statement in the file (before any import); 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 in com/smarthome/; mismatch = won’t compile.
  • Import βž” pull a class from another package into scope: import java.util.ArrayList; β€” then use ArrayList unqualified.
  • Order βž” package line β†’ import lines β†’ 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.java module 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 only to a named module); unexported packages stay module-private even if public.
  • 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.
  • πŸ’‘ package not first βž” any code (even an import) before the package line is a compile error.
  • πŸ’‘ Path β‰  name βž” the on-disk directory structure must mirror the dotted package name exactly.

🧠 Active Recall