Access modifiers
What you will learn
Access modifiers determine which code may use a type or member. They help keep implementation details behind a small public contract. A declaration must be accessible before its name can be used, even if an import or full name identifies it.
- Apply public, package access, protected and private rules to cross-package code.
- Predict access from an unrelated class, a subclass and a nested class.
Use a fresh lab folder for each example, JDK 21 or compatible newer JDK, no external libraries. Create the listed files under src; commands are run from that lab folder. The source compatibility target is Java 21; Java 25 execution is not yet verified.
Keep an internal method package-accessible
package demo.stock;public class Stock { private int quantity; public Stock(int quantity) { if (quantity < 0) throw new IllegalArgumentException("Negative stock"); this.quantity = quantity; } public int quantity() { return quantity; } int capacity() { return 100; }}package demo.stock;public class StockReport { public static String report(Stock stock) { return stock.quantity() + "/" + stock.capacity(); }}package demo.app;import demo.stock.Stock;import demo.stock.StockReport;public class Main { public static void main(String[] args) { Stock item = new Stock(4); System.out.println(StockReport.report(item)); }}Compile and run:
javac --release 21 -d out src/demo/stock/Stock.java src/demo/stock/StockReport.java src/demo/app/Main.javajava -cp out demo.app.MainExpected output:
4/100StockReport and Stock are in the same package, so capacity() is available to the report. Main uses only public entry points.
Access matrix and protected receiver rule
For ordinary class members in this classpath lab, public permits access from other packages if the enclosing type is accessible; no modifier gives package access; protected gives package access plus qualified subclass access outside the package; private limits access to the enclosing top-level class context, including its nested types. Public and package access are the ordinary choices for top-level classes; protected and private are not valid top-level class modifiers. A public member in a package-private class does not make the class accessible. A subpackage is a different package, not a privileged child. Across packages, a subclass accessing a protected instance member through a receiver must use a receiver whose compile-time type is that subclass or a subtype of it. Merely knowing an object is a Delivery at runtime does not make a Delivery-typed receiver legal inside Express. Protected constructors have additional rules; use super(...) in subclasses rather than assuming ordinary new Base(...) is allowed. Named modules can further limit public access via exports; module rules are deferred.
Use a protected member from another package
package demo.delivery;public class Delivery { protected int baseFee() { return 5; }}package demo.express;import demo.delivery.Delivery;public class Express extends Delivery { public int price() { return baseFee() + 3; } public int peerFee(Express peer) { return peer.baseFee(); }}package demo.app;import demo.express.Express;public class Main { public static void main(String[] args) { Express one = new Express(); System.out.println(one.price()); System.out.println(one.peerFee(new Express())); }}Compile and run:
javac --release 21 -d out src/demo/delivery/Delivery.java src/demo/express/Express.java src/demo/app/Main.javajava -cp out demo.app.MainExpected output:
85Express inherits baseFee and may call it through an Express-typed receiver. The application cannot directly call the protected member.
Access a private field from a nested class
package demo.catalog;public class Shelf { private final String label = "A2"; public static class LabelPrinter { public String print(Shelf shelf) { return "Shelf " + shelf.label; } }}package demo.app;import demo.catalog.Shelf;public class Main { public static void main(String[] args) { Shelf shelf = new Shelf(); Shelf.LabelPrinter printer = new Shelf.LabelPrinter(); System.out.println(printer.print(shelf)); }}Compile and run:
javac --release 21 -d out src/demo/catalog/Shelf.java src/demo/app/Main.javajava -cp out demo.app.MainExpected output:
Shelf A2The nested class is within the same enclosing top-level class as the private field. It receives a Shelf explicitly because a static nested class has no implicit outer instance.
Common mistakes
Do not solve a visibility error by making every field public. Keep invariants private and expose operations that make valid changes. Java access checks are not a security sandbox.
Practice
Create demo.library.Shelf with private int count = 2, public count(), and a package-accessible label() returning A. Add public demo.library.Summary.text(Shelf) returning A:2 and call it from demo.app.Main. Then verify that a direct call to shelf.label() from Main fails to compile.
Hints:
- Place Summary in the exact same package as Shelf.
- Use a public method to expose the intended summary; do not make label public.
Related reference topics: Java Private member access, Java Public member access, Java package access, Java protected member access, Java static nested class. Next: Package layout and dependency boundaries.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Access modifiers — knowledge check
Apply package, visibility and classpath rules in Java 21-compatible fixtures.
Can an unrelated class in demo.app call a package-access method in demo.stock?
Which top-level class declaration is valid?
Express extends Delivery in a different package. Which receiver can Express use for Delivery.baseFee(), a protected instance method?
Can a static nested class access a private field of its enclosing class through an explicit instance?
Does demo.stock.internal share package access with demo.stock?