Intermediate level · Module 4: Packages and Builds with Maven · Lesson 1 of 3
Packages and Access Modifiers
Group related classes into packages and use access modifiers to expose only what other code should use.
In this lesson you will
- Create packages and import classes between them
- Choose the narrowest suitable access modifier
Key concepts
packageimportpackage-privatepublic API
The lesson
A package groups related classes and matches a folder: package org.rescue.library.model; means the file lives in org/rescue/library/model. Package names are lowercase and often start with a reversed domain name to stay unique.
Java has four access levels: private (only the class), package-private with no keyword (the same package), protected (the package plus subclasses) and public (everyone). Start with the most restrictive and open up only when needed.
A good package structure follows responsibilities, for example model for data classes, service for business rules and storage for files or databases. The public classes and methods of a package are its API; everything else can change freely.
Step by step
- Create model, service and storage packages.
- Move each class into the right package and fix the imports.
- Make helper classes package-private.
- Check that main can use only the intended public classes.
Practice activity
Reorganise the library project into packages and reduce the number of public classes and methods to those that are really needed.
Expected result: The project compiles with fewer public members, and each package has a clear purpose.
Check your understanding
-
Which access level has no keyword?
Show answer
Package-private: visible within the same package only.
-
Where must a class in package com.example.model be stored?
Show answer
In the folder com/example/model under the source root.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.