Access Control in Java: Packages, Classes and Members
Access control in Java decides which code is allowed to use a class, field, method or constructor. You set it with the access modifiers public, protected and private, or by writing no modifier at all, which gives package-private access. Packages are the boundary that makes access control work, so this lesson looks at access rules across real packages.
You will see each access level tested from the same package, from a subclass in another package, and from an unrelated package. You will also learn the tricky protected rule, how to control access to whole classes and constructors, and how to design a package with a small public API and hidden implementation classes.
The Four Levels of Access Control in Java
| Modifier | Same class | Same package | Subclass in another package | Any other package |
|---|---|---|---|---|
public | Yes | Yes | Yes | Yes |
protected | Yes | Yes | Yes (through inheritance) | No |
| (none) package-private | Yes | Yes | No | No |
private | Yes | No | No | No |
Read the table from top to bottom: each level is more restricted than the one above it.
Note: You met these modifiers in Access Modifiers in Java with single-file examples. Here every example uses separate packages, because that is where the differences actually show up.
Access Control Across Packages: A Full Example
This project has two packages. account holds the Account class and an Auditor in the same package. app holds the program that uses them.
bank/src/com/gocourse/bank/
├── account/
│ ├── Account.java
│ └── Auditor.java
└── app/
└── Main.java
account/Account.java declares one field at each access level:
package com.gocourse.bank.account;
public class Account {
public String holder; // visible everywhere
protected double balance; // package + subclasses
String branchCode; // package-private: this package only
private String pin; // this class only
public Account(String holder, double balance, String branchCode, String pin) {
this.holder = holder;
this.balance = balance;
this.branchCode = branchCode;
this.pin = pin;
}
public boolean checkPin(String attempt) {
return pin.equals(attempt); // private field used inside its own class
}
}
account/Auditor.java is in the same package:
package com.gocourse.bank.account;
public class Auditor {
public static void inspect(Account account) {
System.out.println("holder = " + account.holder); // public: OK
System.out.println("balance = " + account.balance); // protected: OK (same package)
System.out.println("branch = " + account.branchCode); // package-private: OK (same package)
// System.out.println(account.pin); // private: compile error
}
}
app/Main.java is in a different package:
package com.gocourse.bank.app;
import com.gocourse.bank.account.Account;
import com.gocourse.bank.account.Auditor;
public class Main {
public static void main(String[] args) {
Account account = new Account("Asha", 5000.0, "CHN01", "4321");
Auditor.inspect(account);
System.out.println("From app: " + account.holder);
System.out.println("PIN ok? " + account.checkPin("4321"));
}
}
Compile and run from the bank folder:
javac -d out $(find src -name "*.java")
java -cp out com.gocourse.bank.app.Main
Output:
holder = Asha
balance = 5000.0
branch = CHN01
From app: Asha
PIN ok? true
How it works:
Auditorshares a package withAccount, so it can readpublic,protectedand package-private fields. Onlypinis off limits.Mainlives incom.gocourse.bank.app, so it can use only thepublicparts: the class, the constructor,holderandcheckPin().- The PIN is never exposed. Other code can only ask
checkPin()whether a guess is correct. This is encapsulation enforced by access control.
What the Compiler Says When Access Is Denied
Add a class to the app package that tries to read the restricted fields:
package com.gocourse.bank.app;
import com.gocourse.bank.account.Account;
public class Snoop {
public static void main(String[] args) {
Account account = new Account("Asha", 5000.0, "CHN01", "4321");
System.out.println(account.balance);
System.out.println(account.branchCode);
System.out.println(account.pin);
}
}
Output (compile errors):
src/com/gocourse/bank/app/Snoop.java:8: error: balance has protected access in Account
System.out.println(account.balance);
^
src/com/gocourse/bank/app/Snoop.java:9: error: branchCode is not public in Account; cannot be accessed from outside package
System.out.println(account.branchCode);
^
src/com/gocourse/bank/app/Snoop.java:10: error: pin has private access in Account
System.out.println(account.pin);
^
3 errors
How it works:
- Each access level has its own error message, which helps you see at once which rule was broken.
- Access control is checked at compile time. The code never runs, so there is no way to reach these fields by accident.
| Error message | Meaning |
|---|---|
x has private access in C | x is private; only code inside class C can use it |
x is not public in C; cannot be accessed from outside package | x is package-private |
x has protected access in C | x is protected and you are not using it through inheritance |
Protected Access From a Subclass in Another Package
A subclass in a different package can use protected members it inherits. Here SavingsAccount lives in its own savings package:
package com.gocourse.bank.savings;
import com.gocourse.bank.account.Account;
public class SavingsAccount extends Account {
private final double rate;
public SavingsAccount(String holder, double balance, double rate) {
super(holder, balance, "CHN01", "0000");
this.rate = rate;
}
public void addInterest() {
balance = balance + balance * rate; // protected: OK through inheritance
System.out.println(holder + " new balance: " + balance);
}
public static void main(String[] args) {
SavingsAccount savings = new SavingsAccount("Ravi", 10000.0, 0.04);
savings.addInterest();
}
}
javac -d out $(find src -name "*.java")
java -cp out com.gocourse.bank.savings.SavingsAccount
Output:
Ravi new balance: 10400.0
How it works:
balanceisprotected, andSavingsAccountextendsAccount, soaddInterest()can read and change its own inheritedbalance.- The calculation is
10000.0 + 10000.0 × 0.04 = 10400.0. branchCodewould still be off limits here. Package-private members are not visible to subclasses in other packages.
The protected Rule Most Beginners Miss
Outside the package, a subclass may use a protected member only through a reference of its own type (or a subtype of it), such as this. It cannot use it through a plain Account reference, or through a sibling subclass.
package com.gocourse.bank.savings;
import com.gocourse.bank.account.Account;
public class Transfer extends Account {
public Transfer() {
super("System", 0.0, "HQ", "0000");
}
void copyFrom(Account other, SavingsAccount savings) {
double own = this.balance; // OK: our own inherited field
double sav = savings.balance; // Error: SavingsAccount is not a Transfer
double plain = other.balance; // Error: plain Account reference
}
}
Output (compile errors):
src/com/gocourse/bank/savings/Transfer.java:12: error: balance has protected access in Account
double sav = savings.balance; // Error: SavingsAccount is not a Transfer
^
src/com/gocourse/bank/savings/Transfer.java:13: error: balance has protected access in Account
double plain = other.balance; // Error: plain Account reference
^
2 errors
How it works:
protectedmeans "my subclasses may use the part they inherited".this.balanceis the partTransferinherited, so it is allowed.othermight be any account, andsavingsbelongs to a different subclass.Transferhas no right to their internals, even though it is also a subclass ofAccountand is in the same package asSavingsAccount.- Inside the
accountpackage itself, all three lines would compile, becauseprotectedalso includes package access.
Controlling Access to Whole Classes
A top-level class (one not nested in another class) can only be public or package-private.
| Top-level class modifier | Who can use the class |
|---|---|
public class Notifiers | Any package (the file must be named Notifiers.java) |
class EmailNotifier | Only classes in the same package |
private class / protected class | Not allowed for top-level classes: compile error |
When a class is package-private, even its public methods are unreachable from other packages, because the class name itself cannot be used there. The real-world example at the end of this lesson shows the error you get.
Restricting Constructors
Access modifiers on constructors control who can create objects. Two common patterns are:
- A
privateconstructor in a utility class, so no one creates useless instances. - A
privateconstructor plus a static factory method or builder, so objects are only created in a controlled way.
public class Course {
private final String title;
private Course(String title) { // private constructor
this.title = title;
}
static class Builder {
private String title = "Untitled"; // private field of the nested class
Builder title(String value) {
this.title = value;
return this;
}
Course build() {
return new Course(title); // nested class calls the private constructor
}
}
public static void main(String[] args) {
Builder builder = new Builder().title("Java Tutorial");
System.out.println("Builder title: " + builder.title); // outer class reads nested private field
Course course = builder.build();
System.out.println("Course title: " + course.title);
}
}
Output:
Builder title: Java Tutorial
Course title: Java Tutorial
How it works:
- No code outside
Coursecan callnew Course(...). The only way to get aCourseis throughBuilder. privateaccess covers the whole top-level class, including its nested classes. That is whyBuilder.build()can call the private constructor andmaincan readbuilder.title.- Builders and factories let a class check its input or pick an implementation before an object exists.
Default Access in Interfaces, Enums and Records
Some kinds of members get an access level automatically:
| Member | Access if you write no modifier |
|---|---|
| Interface method (abstract, default or static) | public |
| Interface field (constant) | public static final |
| Enum constructor | private (cannot be made public) |
Record component accessor, such as name() | public |
| Class or record member with no modifier | package-private |
Because interface methods are always public, a class that implements an interface must declare those methods public as well. Leaving the modifier off in the class would try to reduce access, which is a compile error.
Access Control and Java Modules
Since Java 9, modules add one more layer above packages. A public class in a module is visible to other modules only if its package is exported in module-info.java.
| Level | Boundary | Controlled by |
|---|---|---|
| Member | Class | private, package-private, protected, public |
| Class | Package | public or package-private class |
| Package | Module | exports in module-info.java |
For classpath programs like the ones in this lesson, public means "visible everywhere". In modular programs, public means "visible everywhere the package is exported". You will see this in the Java Modules lesson.
Real-World Example: A Public API With Hidden Implementations
Good packages expose a small public API and hide everything else. This notification package lets apps send email and SMS alerts, but apps never see the implementation classes.
notify/src/com/gocourse/notify/
├── api/
│ ├── Notifier.java public interface
│ ├── Notifiers.java public factory, private constructor
│ ├── EmailNotifier.java package-private
│ └── SmsNotifier.java package-private
└── app/
└── AlertApp.java
api/Notifier.java:
package com.gocourse.notify.api;
public interface Notifier {
String send(String to, String message); // interface methods are public by default
}
api/Notifiers.java:
package com.gocourse.notify.api;
public final class Notifiers {
private Notifiers() { } // no one can create a Notifiers object
public static Notifier email() {
return new EmailNotifier();
}
public static Notifier sms() {
return new SmsNotifier(160);
}
}
api/EmailNotifier.java:
package com.gocourse.notify.api;
// Package-private class: an implementation detail of the api package
class EmailNotifier implements Notifier {
@Override
public String send(String to, String message) {
if (!isValidAddress(to)) {
return "REJECTED email to " + to;
}
return "EMAIL to " + to + ": " + message;
}
private boolean isValidAddress(String address) {
return address.contains("@") && address.indexOf('@') < address.lastIndexOf('.');
}
}
api/SmsNotifier.java:
package com.gocourse.notify.api;
// Package-private class with a package-private constructor
class SmsNotifier implements Notifier {
private final int maxLength;
SmsNotifier(int maxLength) {
this.maxLength = maxLength;
}
@Override
public String send(String to, String message) {
String text = message.length() > maxLength ? message.substring(0, maxLength) : message;
return "SMS to " + to + " (" + text.length() + " chars): " + text;
}
}
app/AlertApp.java:
package com.gocourse.notify.app;
import com.gocourse.notify.api.Notifier;
import com.gocourse.notify.api.Notifiers;
import java.util.List;
public class AlertApp {
public static void main(String[] args) {
List<Notifier> channels = List.of(Notifiers.email(), Notifiers.sms());
String alert = "Your Java course starts tomorrow at 10 AM.";
System.out.println(channels.get(0).send("asha@gocourse.com", alert));
System.out.println(channels.get(0).send("not-an-email", alert));
System.out.println(channels.get(1).send("+91 98765 43210", alert));
for (Notifier channel : channels) {
System.out.println(channel.getClass().getSimpleName() + " is public? "
+ java.lang.reflect.Modifier.isPublic(channel.getClass().getModifiers()));
}
}
}
javac -d out $(find src -name "*.java")
java -cp out com.gocourse.notify.app.AlertApp
Output:
EMAIL to asha@gocourse.com: Your Java course starts tomorrow at 10 AM.
REJECTED email to not-an-email
SMS to +91 98765 43210 (42 chars): Your Java course starts tomorrow at 10 AM.
EmailNotifier is public? false
SmsNotifier is public? false
Now try to skip the factory from the app package:
package com.gocourse.notify.app;
import com.gocourse.notify.api.EmailNotifier;
import com.gocourse.notify.api.Notifiers;
public class Bypass {
public static void main(String[] args) {
EmailNotifier direct = new EmailNotifier();
Notifiers helper = new Notifiers();
}
}
Output (compile errors, the same EmailNotifier error repeats for each use on line 8):
src/com/gocourse/notify/app/Bypass.java:3: error: EmailNotifier is not public in com.gocourse.notify.api; cannot be accessed from outside package
import com.gocourse.notify.api.EmailNotifier;
^
src/com/gocourse/notify/app/Bypass.java:9: error: Notifiers() has private access in Notifiers
Notifiers helper = new Notifiers();
^
How it works:
- Public contract. Apps depend only on
NotifierandNotifiers. Those two types are the whole public API of the package. - Hidden implementations.
EmailNotifierandSmsNotifierare package-private, so theapppackage cannot name them, import them or create them. The reflection check confirms that neither class is public. - Controlled creation.
Notifiershas a private constructor and public static factory methods. The factory decides which class to return and passes the SMS length limit of 160 characters. - Private helpers.
isValidAddress()is private, so onlyEmailNotifiercan call it."not-an-email"has no@, so the email is rejected. - Freedom to change. Because nothing outside
apican see the implementation classes, you can rename them, merge them or add aWhatsAppNotifierlater without breaking any app code.
For how to set up and compile multi-package projects like this one, see Create Package in Java, and for the import rules used in AlertApp, see Import Package in Java.