JOOPs Through Java
All lessons

Unit 3 · Classes and Objects · 7 min

Access modifiers

Access modifiers decide who is allowed to see a class, field or method: public, private, protected, or default (no keyword).

Why this matters

They are the tool that makes encapsulation possible — hiding data so nobody can corrupt it by accident.

Example

Java
class Account {
    public String holder;      // visible everywhere
    private double balance;    // visible only inside this class
    protected String branch;   // this class, same package, and subclasses
    String ifsc;               // default: same package only

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public double getBalance() {
        return balance;
    }
}

Step by step

  1. 1`public` is open to everyone.
  2. 2`private` is the strictest: only code inside the same class can touch it.
  3. 3`protected` adds access for subclasses, even in other packages.
  4. 4No keyword means 'default' or package-private: same package only.
  5. 5balance is private, so the only way to change it is through deposit(), which validates the amount.

Key points

  • Order from most open to most closed: public > protected > default > private
  • Keep fields private and expose behaviour through public methods
  • A top-level class can only be public or default

Common mistakes

  • Making every field public and calling it OOP
  • Trying to access a private field from another class
  • Expecting protected to mean 'private to the package'

Try it yourself

  • Make all fields of your Student class private and add public getters.
  • Try reading a private field from main and read the compiler error carefully.
Open the practice notebook