Access Control in Java: Packages, Classes and Members

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 227 of 306

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

ModifierSame classSame packageSubclass in another packageAny other package
publicYesYesYesYes
protectedYesYesYes (through inheritance)No
(none) package-privateYesYesNoNo
privateYesNoNoNo

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:

  • Auditor shares a package with Account, so it can read public, protected and package-private fields. Only pin is off limits.
  • Main lives in com.gocourse.bank.app, so it can use only the public parts: the class, the constructor, holder and checkPin().
  • 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 messageMeaning
x has private access in Cx is private; only code inside class C can use it
x is not public in C; cannot be accessed from outside packagex is package-private
x has protected access in Cx 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:

  • balance is protected, and SavingsAccount extends Account, so addInterest() can read and change its own inherited balance.
  • The calculation is 10000.0 + 10000.0 × 0.04 = 10400.0.
  • branchCode would 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:

  • protected means "my subclasses may use the part they inherited". this.balance is the part Transfer inherited, so it is allowed.
  • other might be any account, and savings belongs to a different subclass. Transfer has no right to their internals, even though it is also a subclass of Account and is in the same package as SavingsAccount.
  • Inside the account package itself, all three lines would compile, because protected also 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 modifierWho can use the class
public class NotifiersAny package (the file must be named Notifiers.java)
class EmailNotifierOnly classes in the same package
private class / protected classNot 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 private constructor in a utility class, so no one creates useless instances.
  • A private constructor 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 Course can call new Course(...). The only way to get a Course is through Builder.
  • private access covers the whole top-level class, including its nested classes. That is why Builder.build() can call the private constructor and main can read builder.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:

MemberAccess if you write no modifier
Interface method (abstract, default or static)public
Interface field (constant)public static final
Enum constructorprivate (cannot be made public)
Record component accessor, such as name()public
Class or record member with no modifierpackage-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.

LevelBoundaryControlled by
MemberClassprivate, package-private, protected, public
ClassPackagepublic or package-private class
PackageModuleexports 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:

  1. Public contract. Apps depend only on Notifier and Notifiers. Those two types are the whole public API of the package.
  2. Hidden implementations. EmailNotifier and SmsNotifier are package-private, so the app package cannot name them, import them or create them. The reflection check confirms that neither class is public.
  3. Controlled creation. Notifiers has a private constructor and public static factory methods. The factory decides which class to return and passes the SMS length limit of 160 characters.
  4. Private helpers. isValidAddress() is private, so only EmailNotifier can call it. "not-an-email" has no @, so the email is rejected.
  5. Freedom to change. Because nothing outside api can see the implementation classes, you can rename them, merge them or add a WhatsAppNotifier later 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Access Control in Java: Packages, Classes and Members and get answers drawn from it.

Signed-in readers only.