AI Hints
Home›Java Tutorial›Access Modifiers, Getters and Setters, and toString
Java · Lesson 70 of 120

Access Modifiers

Public and private.

⏱ 2 min read▶ Video at 1:28:11🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Some parts of a class should be used by everyone. Others are private details, that only the class itself should touch. Access modifiers control this.

  • Some parts are public
  • Some are private
  • Modifiers control it

The four levels

Public means any code can use it. Private means only code inside the same class. Protected, and the default with no word, are in between. We'll meet those with inheritance, and packages.

ModifierWho can use it
publiceveryone
protectedsame package + subclasses
(none)same package
privatethis class only

A private balance

The balance is private. Nobody outside the class can change it directly. The only way in is deposit, which is public. And deposit refuses negative amounts, so the balance stays sensible.

Main.javajava
public class Account {
    private String owner;
    private double balance;

    public Account(String owner) {
        this.owner = owner;
    }

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

Trying to cheat

Main tries to set the balance directly, to a million. Run it. Balance has private access. Java won't even compile it. The class protects its own data.

Main.javajava
public class Main {
    public static void main(String[] args) {
        Account acc = new Account("Lena");
        acc.deposit(50);
        acc.balance = 1000000;
    }
}
Output
Main.java:5: error: balance has private access in Account
        acc.balance = 1000000;
           ^
1 error
error: compilation failed
Also uses Account.java
public class Account {
    private String owner;
    private double balance;

    public Account(String owner) {
        this.owner = owner;
    }

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

Summary

Public parts can be used by anyone. Private parts only by the class itself. Make fields private, and offer public methods. Next, getters and setters.

Key takeaways
  • public: everyone
  • private: this class
  • Private fields
Next up: Getters and Setters — controlled access