Explain it simply
Explain it simply
Think of a bank. The deposit counter is open to everyone (public). The staff room is only for employees of this branch (package-private). The vault can be opened only by one designated person (private). A customer cannot reach into the vault directly; deposits and withdrawals go through the counter.
Java's access modifiers are those doors for your code. Non-access modifiers describe a member's nature rather than who can see it: static means "one for the whole bank", like the bank's name, and final means "set once, never changed".
Problem → Why → Solution
The problem: code outside the class edits balance directly
In this Account class, deposit() rejects negative amounts, yet the balance field itself is open to anyone. A developer writing report code types account.balance = -500; "just to test something", and every check inside deposit() becomes pointless. The compiler accepts it happily.
public class Main {
public static void main(String[] args) {
Account account = new Account();
account.deposit(-100); // rejected by the rule
account.balance = -500; // bypasses the rule completely
System.out.println(account.balance); // -500
}
}
class Account {
int balance; // no modifier: visible to the whole package
void deposit(int amount) {
if (amount > 0) balance += amount;
}
}Why does private fix it?
Change the field to private int balance; and no code outside Account can see it: account.balance = -500; becomes the compile error "balance has private access in Account". deposit() is now the only way to change the balance, so there is no way around the rule.
Core concept: four access levels, plus static and final
Access modifiers draw a class's API boundary. Java has four levels, and package-private, written with no keyword, is the default. Because of its name, protected sounds narrower than package-private, but it is actually wider: it allows every class in the same package plus subclasses in other packages. A top-level class can only be public or package-private, and a file may hold just one public top-level class, named after the file.
| Modifier | Visible from |
|---|---|
| public | Everywhere |
| protected | Same package + subclasses in other packages |
| (no keyword) package-private | Classes in the same package only |
| private | Only inside the declaring class |
static means the member belongs to the class itself, with one copy, rather than to each object. With static int openedCount, every Account object shares a single counter no matter how many are created. A static method is called through the class name, as in Account.opened(), and since there is no object behind the call it cannot use instance fields directly.
final has three meanings depending on where it appears. A final variable or field can be assigned only once. A final method cannot be overridden by a subclass. A final class, such as String, cannot be extended. static final together makes a constant such as BANK_NAME, conventionally written in UPPER_SNAKE_CASE. abstract arrives in the Abstraction lesson, and modifiers such as sealed, synchronized and volatile appear in later lessons where they matter.
When this lesson's examples run with java Main.java, every class in the file sits in the same unnamed package. So Main can see Account's package-private and protected members; only the private ones are hidden. Seeing the real difference between protected and package-private needs a project with two packages, which we revisit in the Inheritance lesson.
- Who may see it? → access modifier
- Object's or class's? → static
- May it change? → final
When in doubt, start with the narrowest access, private, and widen only when needed.
General pattern
class ClassName {
public static final Type CONSTANT = value; // shared, never changes
private static Type sharedCounter; // shared, hidden
private final Type id; // per object, set once
private Type state; // per object, hidden
public ReturnType action(Type arg) { ... } // the public API
static ReturnType helper() { ... } // called as ClassName.helper()
private void internalStep() { ... } // implementation detail
}The usual order is access, then static, then final, then the type. Keep fields private, make public only the methods outsiders must call, and mark as static what the whole class shares.
Example: an Account with private state and a static counter
This example shows four kinds of modifier in one class: a static final constant, a private static counter, a private final field, and public methods guarding a private field. Uncomment the commented line to see the private-access error yourself. Also predict what mya.deposit(-300) does, and how many accounts the static counter reports at the end.
public class Main {
public static void main(String[] args) {
System.out.println(Account.BANK_NAME);
Account aung = new Account("Aung", 5000);
Account mya = new Account("Mya", 1200);
aung.deposit(2500);
mya.deposit(-300); // rejected inside deposit()
// aung.balance = 1_000_000; // compile error: balance has private access
System.out.println(aung.owner() + ": " + aung.balance());
System.out.println(mya.owner() + ": " + mya.balance());
System.out.println("Accounts opened: " + Account.opened());
}
}
class Account {
static final String BANK_NAME = "Demo Bank";
private static int openedCount = 0;
private final String owner;
private int balance;
Account(String owner, int balance) {
this.owner = owner;
this.balance = balance;
openedCount++;
}
public void deposit(int amount) {
if (amount > 0) {
balance += amount;
}
}
public String owner() { return owner; }
public int balance() { return balance; }
static int opened() { return openedCount; }
}Code breakdown
- Class-level constant
static final String BANK_NAME = "Demo Bank";Being static, it is read as Account.BANK_NAME without any object; being final, nobody can reassign it.
- Shared counter
private static int openedCount = 0;All Account objects share this one counter, so openedCount++ in the constructor runs once per account and ends at 2. It is private, so outside code cannot tamper with it.
- Per-object, set once
private final String owner;Each object has its own owner, assigned once in the constructor and fixed afterwards. Outsiders can only read it through owner().
- The only door to balance
public void deposit(int amount) {With balance private, this method is the only way to change it. if (amount > 0) rejects mya.deposit(-300), so Mya keeps 1200.
- Static method call
System.out.println("Accounts opened: " + Account.opened());opened() is static, so it is called through the class name with no object. Trying to use an instance field such as balance inside it would be a compile error.
Demo Bank
Aung: 7500
Mya: 1200
Accounts opened: 2A final reference is not an immutable object
final locks the reference stored in the variable, not the object it points to. With final int[] seats you cannot make seats point at a new array, but changing the contents, as seats[0] = 42 does, is perfectly legal. A final List<String> still accepts add() and remove(). If the object itself must not change, use an unmodifiable collection such as List.of() or an immutable type such as a record.
import java.util.Arrays;
public class Main {
static final int MAX_SEATS = 3;
public static void main(String[] args) {
final int[] seats = new int[MAX_SEATS];
seats[0] = 42; // allowed: the array object itself is still mutable
// seats = new int[5]; // compile error: cannot assign a value to final variable
System.out.println(Arrays.toString(seats));
}
}The output is [42, 0, 0]. Uncomment the reassignment and you get "cannot assign a value to final variable seats".
In real projects
Where this shows up in real projects
Production code keeps fields such as API keys, password hashes and internal caches private and controls them through a few public methods. For a team that publishes a library, public is a promise: once users call a public method, renaming or removing it breaks their code. Private methods can be refactored freely at any time, which is why teams keep the public surface as small as possible.
static final constants appear everywhere for configuration values, error messages and limits, such as MAX_LOGIN_ATTEMPTS = 5. Mutable static fields, however, are used with great care: on a web server handling many requests at once, several threads updating one static counter can cause a data race, and static state also leaks between tests. In frameworks such as Spring, injecting dependencies into private final fields through the constructor is the standard style.
Common mistakes
Common mistakes
1. Believing final makes the object immutable
With private final List<String> tags; and a getTags() that returns the list itself, a caller can run getTags().clear() and wipe its contents. final only protects the reference. Return List.copyOf(tags) or an unmodifiable view instead.
2. Making per-object data static
Writing static int balance; makes every account share one balance, so Aung's deposit raises Mya's balance too. Anything that should differ between objects must not be static.
3. Making everything public "just in case"
Making fields and helper methods public "in case someone needs them later" lets outside code depend on them, which makes later changes painful. Start private and widen only when there is a real need, and remember that protected is wider than package-private, not narrower.
Best practices
Best practices
- Start every new field as private, and add final when it never needs to change.
- Avoid mutable static fields; reserve static mainly for constants (static final) and stateless helper methods.
- Before adding a public method, ask whether you are willing to support it for years.
Mini challenge
Mini challenge: numbered tickets
Write a Ticket class that numbers each ticket automatically. Outside code must not be able to change any number.
- Use private static int nextNumber = 1 and private static final String PREFIX = "TKT-"
- private final int number and private final String event are set once in the constructor
- public String label() returns a String like "TKT-1 (Concert)"
- static int issued() returns how many tickets have been issued
public class Main {
public static void main(String[] args) {
// TODO: issue two "Concert" tickets and one "Football" ticket
// TODO: print each label(), then "Issued: " + Ticket.issued()
}
}
class Ticket {
// TODO: a shared counter starting at 1 and a constant prefix "TKT-"
// TODO: per-ticket number and event that can never change
Ticket(String event) {
// TODO: store the event, take the next number, advance the counter
}
// TODO: public label() -> "TKT-1 (Concert)"
// TODO: static issued() -> number of tickets created so far
}Expected: TKT-1 (Concert) TKT-2 (Concert) TKT-3 (Football) Issued: 3
Show hint
In the constructor, do this.number = nextNumber; and then nextNumber++;. issued() can simply return nextNumber - 1, or you can keep a separate static counter.
Show solution
public class Main {
public static void main(String[] args) {
Ticket first = new Ticket("Concert");
Ticket second = new Ticket("Concert");
Ticket third = new Ticket("Football");
System.out.println(first.label());
System.out.println(second.label());
System.out.println(third.label());
System.out.println("Issued: " + Ticket.issued());
}
}
class Ticket {
private static int nextNumber = 1;
private static final String PREFIX = "TKT-";
private final int number;
private final String event;
Ticket(String event) {
this.event = event;
this.number = nextNumber;
nextNumber++;
}
public String label() {
return PREFIX + number + " (" + event + ")";
}
static int issued() {
return nextNumber - 1;
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Access levels: public > protected > package-private (no keyword) > private; protected is wider than package-private.
- Keep fields private and let them change only through public methods that check the rules.
- A static member belongs to the class and is shared by all objects; a static method has no this.
- final means assign once (variables), no overriding (methods), no subclassing (classes), and it never makes the referenced object immutable.