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.Movieandcom.thirdparty.catalog.Movieare two different classes, even though both are calledMovie.
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:
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:
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.