Skip to content

Packages: grouping your classes

โ˜• Java 17 ยท Organizing Your Code with Packages and Imports ยท 1/3

Why packages?

A streaming application quickly grows: content classes, user classes, platform classes. A package is a named group of related classes, like a folder:

com.netflix.content     Movie, Series, Episode
com.netflix.user        User, Subscription
com.netflix.platform    StreamingPlatform, ContentType

Packages bring two things:

  • Organization: related classes live together.
  • Unique names: a class's full name includes its package. com.netflix.content.Movie and com.thirdparty.catalog.Movie are two different classes, even though both are called Movie.

That full name is the fully qualified class name.

Naming convention

Package names are lowercase words separated by dots. Companies usually start with their domain name reversed: com.netflix.content, com.netflix.user.

Declaring a package

The package statement says which package a class belongs to:

package com.netflix.content;

public class Movie {
    private String title;
    private int releaseYear;
}

Three rules apply:

Rule Detail
First statement package comes before any other code; only comments and blank lines may precede it
One per file a file belongs to exactly one package
Matches the folders com.netflix.content means the file sits in com/netflix/content/

So Movie.java lives here:

project-root/
โ””โ”€โ”€ com/
    โ””โ”€โ”€ netflix/
        โ””โ”€โ”€ content/
            โ””โ”€โ”€ Movie.java

A class without a package statement belongs to the default package. That's fine for a first exercise, but real code always declares one.

Once classes live in different packages, they need a way to find each other. That's the job of import.

๐Ÿ’ป Code: Java17_Part_1_Fundamentals_Core_Syntax on GitHub

Next: imports โ†’