Packages and organization
On this page 8 topics
Overview
Topics
- Packages
- imports
- visibility
- cohesive class design
Learn first
57 min of reading · 2 h of practice (estimate)
Learning outcomes
- Organize classes into packages that match folder structure and use imports correctly.
- Use package-private visibility to hide implementation classes.
- Group classes by feature rather than by technical type, and justify it.
Lessons
Lab and exercises
Lab
BEG-027-LAB1 · Bank Accounts v5
Outcomes: 1, 2, 3 · Time: ~1.5 h Reorganize Bank Accounts into feature packages (account, customer, notification) with a minimal public surface. Write two sentences justifying feature over layer packaging. Acceptance: only intended classes are public.
Exercises (assessment: refactoring exercise)
| ID | Outcome | Task |
|---|---|---|
| BEG-027-EX01 | 1 | Give the folder path and package line for class Invoice in package com.acme.billing. |
| BEG-027-EX02 | 1 | Fix the clash: your code needs both java.util.Date and java.sql.Date. |
| BEG-027-EX03 | 2 | A class RateTable is used only by Account. Which modifier should it have and why? |
| BEG-027-EX04 | 3 | Group these into packages by feature: OrderController, OrderService, OrderRepository, UserController, UserService. |
| BEG-027-EX05 | 1, 2, 3 | Refactoring exercise: take a provided project in the default package and reorganize it with a small public surface. |
Show solutions
- EX01
com/acme/billing/Invoice.javawithpackage com.acme.billing;. - EX02 Import one (
import java.util.Date;) and writejava.sql.Datein full where needed. - EX03 Package-private (no modifier): only its package needs it, and hiding it keeps the public surface small.
- EX04
order/(the three Order classes) anduser/(UserController,UserService). Justification: related code together, helpers can be package-private. - EX05 Graded on: correct
packagelines and folders, compiles and runs, helpers package-private, no use of the default package.
Quiz
Outcomes: O1 packages and imports · O2 package-private · O3 feature vs layer.
A self-check for you: nothing is graded, saved or sent anywhere. Choose an answer, then check it. You can try again as often as you like.
Practical part
Refactoring exercise BEG-027-EX05, the other exercises, and Bank Accounts v5. Pass: project compiles in feature packages and only intended classes are public.
Common mistakes
One giant default package; everything public.
Assessment
Refactoring exercise.
Career relevance
Modular monoliths (MID-059) start here.