Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Classes, Objects and Memory

    Packages and Imports

    A package is a named group of related classes, matching a folder on disk. Names are usually a reversed web domain:

    Chapter 10 of 102 min read

    The Plain Picture#

    A library with thousands of books doesn't put them on one shelf. It has sections — Science, History — and within them sub-sections. Two books can have the same title if they're in different sections.

    The Real Names#

    • A package is a named group of related classes, matching a folder on disk. Names are usually a reversed web domain: com.studybuddy.quiz.

    • The fully qualified name of a class includes its package: java.util.ArrayList, com.studybuddy.quiz.Quiz.

    • import lets you use a class by its short name. import java.util.*; imports every class in java.util.

    • java.lang is imported automatically — that's why String, Math, Integer and System need no import.

    Under the Hood#

      src/main/java/
      └── com/studybuddy/
          ├── model/
          │   ├── Student.java        package com.studybuddy.model;
          │   └── Note.java
          └── quiz/
              └── QuizService.java    package com.studybuddy.quiz;
                                      import com.studybuddy.model.Student;
    • Each .java file starts with its package line, then import lines, then the class.

    • A file can hold only one public top-level class, named like the file.

    • Classes in the same package can see each other's non-private members (Object-Oriented Programming explains access levels).

    • Real projects are built with a build tool — Maven or Gradle — which compiles everything, downloads libraries (dependencies) and runs tests. src/main/java/ is the standard folder layout they expect. You'll see the Python equivalents in Python Packaging and Tools (coming soon).

    For DSA practice you won't need packages at all: LeetCode gives you one class, and single-file programs run with java Main.java.

    Check yourself

    3 questions
    1

    What is a package, and what does it correspond to on disk?

    Show answer

    A named group of related classes; a folder (matching the package name).

    2

    Why doesn't String need an import?

    Show answer

    It's in java.lang, which is imported automatically.

    3

    How many public top-level classes can one file contain?

    Show answer

    One, and the file must be named after it.