Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 201 ยท Object-Oriented Programming

Access Modifiers

Learn Java's access modifiers - public, protected, package-private and private - with a clear table, class-level privacy, private constructors and practical rules.

Every class you write has two audiences: the code inside it, which needs to see everything, and the code that uses it, which should see only what it needs. Access modifiers draw that line. They are the keywords public, protected and private (plus the "no keyword" default) that decide which other code may use a class, field, method or constructor.

This matters more than it first seems. Whatever other code can reach, other code will reach, and then you can never change it without breaking someone. Keeping details private is what lets you fix, speed up or redesign a class later. In this lesson you'll learn the four access levels, the subtle rules around them (privacy is per class, not per object; protected is wider than most people think), and the guidelines professionals follow.

The four access levels

From most open to most closed:

Modifier Same class Same package Subclass in another package Any other code
public yes yes yes yes
protected yes yes yes no
(none): package-private yes yes no no
private yes no no no
  • public: usable from anywhere. This is your class's official API.
  • protected: usable in the same package, and in subclasses, even ones in other packages.
  • package-private (no modifier): usable only by code in the same package. There's no keyword for it; you get it by writing nothing.
  • private: usable only inside the top-level class that declares it.

A package is a named group of related classes, such as java.util or com.example.billing. All the examples on this page live in one file, which means one package, so package-private and protected members behave like public ones here. private is the level you can see working in a single file, so most demos focus on it.

What each modifier can be applied to

Java
public class Invoice {              // top-level class: public or package-private only
    private int number;             // fields: any of the four
    protected void recalculate() {} // methods: any of the four
    Invoice() {}                    // constructors: any of the four (here package-private)

    private static class Line {}    // nested classes: any of the four
}
  • A top-level class can only be public or package-private. private class Invoice at the top level is a compile error, because "private to what?" has no answer.
  • A source file may contain at most one public top-level class, and its name must match the file name (Invoice.java). That rule is why examples here start with public class Main in Main.java.
  • Local variables and parameters never take access modifiers. They're already visible only inside their method (Variable Scope).

private: hiding the details

Here's what happens when outside code tries to reach a private field. This example fails to compile on purpose:

Java Using a private field from outside fails

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compiler stops with error: balance has private access in Account, pointing at the line in main. Delete that line and the program prints 150. The only ways to change the balance are the methods Account chooses to offer, and deposit can refuse bad amounts. That guarantee is the foundation of encapsulation, the next lesson.

private is per class, not per object

A common surprise: private restricts access to the code of a class, not to one object. Any method of Money can read the private fields of any Money object, not just this:

Java One object reading another's private fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice the last line, too: the nested class Formatter reads m.cents. A nested class is part of its enclosing class, so they share private access in both directions. That's what makes methods like equals, compareTo and plus possible without public getters.

Package-private: the default

When you leave out the modifier, the member is visible to every class in the same package and nothing outside it. It's a good fit for helpers that several classes in one package share but that aren't part of the public API:

Java
package com.example.shop;

public class Cart {                     // used by other packages
    public void checkout() {
        Totals totals = PriceCalculator.compute(this);   // same package: fine
        // ...
    }
}

class PriceCalculator {                 // package-private: invisible outside com.example.shop
    static Totals compute(Cart cart) { /* ... */ return null; }
}

Code in com.example.web can use Cart but can't even name PriceCalculator. Note that package-private is the default, not the recommended choice for everything: beginners often get it simply by forgetting to write private.

Packages aren't nested for access purposes. com.example.shop and com.example.shop.internal are two unrelated packages, and package-private members of one are invisible to the other.

protected: for subclasses

protected opens a member to subclasses, which you'll build in Inheritance. Two details are easy to miss:

  1. protected includes the package. A protected member is visible to every class in the same package, subclass or not. It's wider than package-private, not narrower.
  2. In another package, a subclass may use the member only through its own type. A subclass can touch the inherited protected member on this or on objects of its own class, but not on arbitrary instances of the parent:
Java
package com.example.base;
public class Shape {
    protected int sides;
}
Java
package com.example.app;
import com.example.base.Shape;

public class Triangle extends Shape {
    void setUp(Triangle other, Shape someShape) {
        this.sides = 3;         // OK: our own inherited field
        other.sides = 3;        // OK: other is a Triangle
        someShape.sides = 3;    // error: sides has protected access in Shape
    }
}

The idea is that Triangle may manage the triangle part of shapes, but not reach into a Square it happens to hold as a Shape.

Use protected sparingly. Every protected member is a promise to all future subclasses, which is almost as hard to change as public.

Private constructors

Constructors take access modifiers too, and a private constructor is a powerful tool. It means no other class can call new, so the class controls how its objects come into being:

Java Private constructors: factory methods and utility classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two patterns appear here:

  • Static factory methods. ofCelsius and ofFahrenheit have names that say what the number means, which two constructors with the same double parameter couldn't do. The JDK uses this everywhere: List.of, LocalDate.of, Integer.valueOf.
  • Utility classes. TextTools only holds static methods, so a private constructor stops anyone from creating pointless instances. java.lang.Math is built the same way. See Static Fields, Methods and Blocks.

Private constructors are also how enums and singletons guarantee a fixed set of instances (Enums).

Access and overriding

When a subclass overrides a method, it may keep the same access or make it more open, but never more restrictive. Code that works with the parent type must be able to call the method on any subclass:

Java
class Animal {
    public String sound() { return "..."; }
}

class Cat extends Animal {
    @Override
    protected String sound() { return "meow"; }   // compile error
}

The compiler explains: sound() in Cat cannot override sound() in Animal, followed by attempting to assign weaker access privileges; was public.

For the same reason, every method that implements an interface method must be public, because interface methods are implicitly public. You'll see the full overriding rules in Polymorphism and Method Overriding.

Beyond the four levels

  • Modules add a layer above packages. A public class in a module is only reachable from other modules if its package is exported in module-info.java. That's how the JDK hides internal packages such as jdk.internal.misc (The Java Module System).
  • Reflection can switch access checks off with setAccessible(true), and frameworks use that to fill private fields. Modules can block it. That's a tool for frameworks, not a way around your own design (Reflection).
  • Interfaces have their own defaults: methods are public unless you mark them private (allowed since Java 9 for helper methods), and fields are always public static final (Interfaces).

Access modifiers are about design, not security. They stop honest code from depending on details; they don't protect secrets from someone who can run code in your process.

Guidelines

Start closed and open up only when there's a reason:

  1. Fields: private. Almost always. The exceptions are constants (public static final) and record components, which are exposed through accessor methods anyway.
  2. Methods: as private as possible. Helper methods that only the class uses are private. Make a method public when it's a deliberate part of what the class offers.
  3. Classes: package-private unless other packages need them. A smaller public surface is easier to maintain.
  4. protected: only for a planned extension point. If you didn't design a class for subclassing, don't scatter protected around it.
  5. Never widen access just to make a test compile. Test through the public API, or put the test in the same package so package-private members are reachable.

A useful question for every member: "If I rename or delete this next year, whose code breaks?" If the answer should be "only mine", make it private.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which code can use a member declared with no access modifier?

    No modifier means package-private. Every class in the same package can use the member; code in other packages, even subclasses, cannot.
  2. 2. Class Point has private int x; and a method boolean sameX(Point other) { return x == other.x; }. What happens?

    Code inside Point may access the private members of any Point object, not just this. That's how equals and compareTo methods compare fields.
  3. 3. Which statement about protected is true?

    protected includes everything package-private allows (the whole package) and adds subclasses in other packages. Top-level classes can only be public or package-private.
  4. 4. A parent class has public void save(). What can an overriding method in a subclass be declared as?

    An override can't reduce access. Since the original is public, the override must be public too. A protected original could be overridden as protected or public.
  5. 5. Why does a utility class like Math have a private constructor?

    A class with only static members has no use for objects. A private constructor makes new Math() a compile error and documents that intent.

Summary

  • Java has four access levels: public (everywhere), protected (package + subclasses), package-private (no keyword, same package) and private (same top-level class).
  • Top-level classes are public or package-private; one public top-level class per file, named like the file.
  • private is per class: any code in the class (and its nested classes) can access the private members of any instance.
  • protected is wider than package-private; in another package, subclasses may use it only through their own type.
  • Private constructors enable static factory methods, utility classes, enums and singletons.
  • Overrides may widen access but never narrow it.
  • Default to private fields and the smallest public surface that does the job.

Next: Encapsulation, Getters and Setters, where you'll use private state and well-chosen methods to keep objects valid.