Java Access Modifiers: private, Package, protected and public (OCP 21)
The four Java access levels for the OCP 21 exam: private, package (no keyword), protected and public, with the full access table, why protected through a superclass reference fails in another package, protected constructors and static members, and how modules affect public.
kvi5hnuCode Sprout team member8 min readOn this page
Access modifiers decide which code is allowed to use a member, meaning a field or a method (constructors and nested types follow the same rules). They are the basis of encapsulation: you keep the data private and give callers only the operations they need. On the exam, access questions usually show several classes in different packages and ask which lines compile. This article goes through the four levels from the most restrictive to the least.
| Level | Keyword | Can be used from |
|---|---|---|
| private | private | the same class only |
| package | (none) | the same class, plus other classes in the same package |
| protected | protected | package access, plus subclasses in other packages |
| public | public | anywhere |
Each level includes everything the level above it allows.
private: the same class only
package harbor.boats;
public class Ferry {
private int fuel = 80;
private void refuel() { fuel = 100; }
public void prepare() {
refuel(); // fine: same class
System.out.println(fuel);
}
}
package harbor.boats;
public class Deckhand {
void help(Ferry f) {
f.refuel(); // DOES NOT COMPILE: refuel() has private access in Ferry
System.out.println(f.fuel); // DOES NOT COMPILE
}
}
Being in the same package doesn't help, and neither does being in the same source file: a second top-level class in Ferry.java still can't use fuel. There's one exception. Nested classes share access with their enclosing class, so a static nested or inner class declared inside Ferry can read fuel, and Ferry can read the private members of its nested classes. Java 11 formalized this as "nest-based access control" (JEP 181).
Package access: no keyword
When a member has no access modifier, only code in the same package can use it:
package harbor.boats;
public class Tug {
int horsepower = 900; // package access
void push() { System.out.println("push " + horsepower); }
}
package harbor.boats; // same package
public class Pilot {
void guide(Tug t) {
t.push(); // fine
System.out.println(t.horsepower); // fine
}
}
package harbor.cargo; // different package
import harbor.boats.Tug;
public class Crane {
void lift(Tug t) {
t.push(); // DOES NOT COMPILE: push() is not public in Tug
}
}
The Tug class itself is public, so Crane can import it and refer to it. Its members, though, are visible only inside harbor.boats. Class-level access and member-level access are checked separately.
Package access is sometimes called package-private or default access, but you never write default (article 25).
protected: package plus subclasses
protected allows everything package access does, and adds subclasses in other packages. Subclasses are declared with extends, which Chapter 6 covers in depth. Here's the setup:
package lib;
public class Gadget {
protected int prot = 3;
protected void tick() { System.out.println("tick " + prot); }
}
From the same package: always allowed
package lib;
public class Neighbor {
void use() {
Gadget g = new Gadget();
g.tick(); // fine: same package
System.out.println(g.prot); // fine
}
}
From a subclass in another package: through inheritance
package other;
import lib.Gadget;
public class Sub extends Gadget {
void use() {
tick(); // fine: inherited member
System.out.println(prot); // fine
System.out.println(this.prot); // fine
}
}
From an unrelated class in another package: never
package other;
import lib.Gadget;
public class Stranger {
void use(Gadget g) {
g.tick(); // DOES NOT COMPILE: tick() has protected access in Gadget
}
}
The tricky part: the reference type

Inside Sub, protected members of Gadget can be used through this, through inheritance, or through a reference whose type is Sub or a subclass of Sub. They can't be used through a Gadget reference, even when that reference points to a Sub object:
package other;
import lib.Gadget;
public class Sub extends Gadget {
void helpSub(Sub s) {
s.tick(); // fine: reference type is Sub
}
void helpGadget(Gadget g) {
g.tick(); // DOES NOT COMPILE
}
void helpDisguised() {
Gadget g = new Sub();
g.tick(); // DOES NOT COMPILE: the reference type is what counts
}
}
Why does Java work this way? A Gadget reference could point to any subclass of Gadget, including an unrelated OtherSub written by someone else. protected means "a subclass can use what it inherits", not "a subclass can reach into every other Gadget". So when the code is in a different package from Gadget, the compiler checks two things:
- Is the code inside a subclass of
Gadget(here,Sub)? - If the member is accessed through a reference, is the reference's type
Subor a subclass ofSub?
A reference to a sibling subclass, such as class Other extends Gadget, fails the second check, too.
Two related cases:
- Protected
staticmembers have no object to worry about, so a subclass in another package can use them through the class name:Gadget.someStaticProtcompiles insideSub. - A protected constructor can be called from a subclass in another package through
super(), but not withnew Gadget().
public: anywhere
package harbor.boats;
public class Dock {
public String name = "Pier 4";
public void moor() { System.out.println("moored at " + name); }
}
Any class, in any package, can import Dock and use name and moor().
The full table
A method in the class on the left can access a member with the level at the top:
private | package | protected | public | |
|---|---|---|---|---|
| the same class | yes | yes | yes | yes |
| another class in the same package | no | yes | yes | yes |
| a subclass in a different package | no | no | yes* | yes |
| an unrelated class in a different package | no | no | no | yes |
* through inheritance, or through a reference of the subclass's own type.
Which modifiers go where?
- Members (fields, methods, constructors and nested types) can use any of the four levels.
- Top-level classes, interfaces, enums and records can only be
publicor package-access. Aprivateorprotectedtop-level class doesn't compile. - Local variables can't have an access modifier at all (article 26).
- A source file can contain at most one
publictop-level type, and the file must have the same name as that type.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Since Java 17 (JEP 403), the JDK's internal packages are strongly encapsulated, and reflection can't break into them without
--add-opens. That's module access (articles 73–77), layered on top of the four access levels here.
Exam traps from this article
A complete example
A single runnable file can't contain several packages, so this program shows the rules that apply inside one package, then uses reflection to read each member's access level and prints the access table as code.
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Solution {
// A class that hides its data and exposes only what callers need.
static class Locker {
private int code; // only Locker's own code (and its nest)
String building = "B2"; // package access: no keyword
protected int size = 40; // package + subclasses
public final String id; // anyone
public Locker(String id, int code) {
this.id = id;
this.code = code;
}
public boolean open(int attempt) { // public operation guarding private data
return attempt == code;
}
private void reset() {
code = 0;
}
protected String describe() {
return id + " in " + building + ", " + size + " L";
}
}
// A subclass: inherits the protected and package members (same package here).
static class BigLocker extends Locker {
BigLocker(String id, int code) {
super(id, code);
size = 80; // inherited protected field
}
@Override
protected String describe() {
return "BIG " + super.describe();
}
}
enum Level { PRIVATE, PACKAGE, PROTECTED, PUBLIC }
enum Caller { SAME_CLASS, SAME_PACKAGE, SUBCLASS_OTHER_PACKAGE, OTHER_PACKAGE }
// The four access rules, written out as code.
static boolean canAccess(Level level, Caller caller) {
return switch (level) {
case PRIVATE -> caller == Caller.SAME_CLASS;
case PACKAGE -> caller == Caller.SAME_CLASS || caller == Caller.SAME_PACKAGE;
case PROTECTED -> caller != Caller.OTHER_PACKAGE;
case PUBLIC -> true;
};
}
static Level levelOf(int modifiers) {
if (Modifier.isPrivate(modifiers)) return Level.PRIVATE;
if (Modifier.isProtected(modifiers)) return Level.PROTECTED;
if (Modifier.isPublic(modifiers)) return Level.PUBLIC;
return Level.PACKAGE;
}
public static void main(String[] args) {
var locker = new Locker("L-17", 4321);
System.out.println("open(1111): " + locker.open(1111) + ", open(4321): " + locker.open(4321));
// Solution and Locker share a top-level class, so private members are reachable here.
System.out.println("code seen from the enclosing class: " + locker.code);
locker.reset();
System.out.println("after reset, open(0): " + locker.open(0));
System.out.println(new BigLocker("L-90", 1).describe());
System.out.println("\n== Members of Locker and their access level");
List<Member> members = new ArrayList<>();
for (Field f : Locker.class.getDeclaredFields()) members.add(f);
for (Method m : Locker.class.getDeclaredMethods()) members.add(m);
members.sort(Comparator.comparing(Member::getName));
for (Member m : members) {
System.out.printf("%-10s %s%n", m.getName(), levelOf(m.getModifiers()));
}
System.out.println("\n== Who can access a member?");
var header = new StringBuilder(String.format("%-24s", "caller \\ member"));
for (Level level : Level.values()) header.append(String.format("%-10s", level));
System.out.println(header.toString().stripTrailing());
for (Caller caller : Caller.values()) {
var row = new StringBuilder(String.format("%-24s", caller));
for (Level level : Level.values()) {
row.append(String.format("%-10s", canAccess(level, caller) ? "yes" : "-"));
}
System.out.println(row.toString().stripTrailing());
}
}
}
Output:
open(1111): false, open(4321): true
code seen from the enclosing class: 4321
after reset, open(0): true
BIG L-90 in B2, 80 L
== Members of Locker and their access level
building PACKAGE
code PRIVATE
describe PROTECTED
id PUBLIC
open PUBLIC
reset PRIVATE
size PROTECTED
== Who can access a member?
caller \ member PRIVATE PACKAGE PROTECTED PUBLIC
SAME_CLASS yes yes yes yes
SAME_PACKAGE - yes yes yes
SUBCLASS_OTHER_PACKAGE - - yes yes
OTHER_PACKAGE - - - yes
Points to notice:
Lockerkeepscodeprivateand exposes apublicopenmethod that checks it. That's encapsulation in its simplest form.maincan readlocker.codeand calllocker.reset()only becauseLockeris nested insideSolution. Moved to its own top-level class, those lines wouldn't compile.BigLockersets the inheritedprotectedfieldsizedirectly and callssuper.describe().- Reflection reports a member with no modifier as package access, because
Modifierhas no flag for it.
Common questions
Is protected more or less restrictive than package access?
Less restrictive. It includes package access and adds subclasses.
Should fields ever be protected or public?
Usually not. Most style guides make fields private and provide methods, and public static final constants are the common exception. protected fields tie subclasses to implementation details.
Can a subclass make an inherited method less accessible?
No. An overriding method must be at least as accessible as the one it overrides (Chapter 6). It can make it more accessible, for example from protected to public.
Does reflection bypass access modifiers?
setAccessible(true) can, but since Java 16 (JEP 396) and Java 17 (JEP 403), the JDK's internal packages are strongly encapsulated and refuse it unless they are explicitly opened. That's not on the exam.
Summary
- From most to least restrictive:
private(same class), package (no keyword: same package),protected(package + subclasses),public(everywhere, subject to module exports). - Class access and member access are checked separately. Top-level types can only be
publicor package-access. - In another package, a subclass can use
protectedinstance members only through inheritance or through references of its own type (or a subtype of it). - Protected
staticmembers can be used through the class name, and a protected constructor only throughsuper(), from subclasses in other packages. - Keep fields
privateand expose behavior through methods. That's the core of encapsulation.
Practice quiz
Test yourself with the access modifiers quiz: 10 exam-style questions with explanations.
Previous: Java Local and Instance Variables, Effectively Final and Varargs (OCP 21)
Next: Java static Members, Static Initializers and Static Imports (OCP 21)
Related reading
- Java Packages and Imports: Wildcards, Conflicts, Compiling and the Class Path (OCP 21)
- Certificates in Java: keytool, Certificate Chains and Signing JAR Files
- Javadoc: Writing Documentation Comments in Java
- Java JAR Files: Creating, Running and Configuring with the Manifest
- Java Package Access and the Class Path

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.