Sub topic 2
Controlling visibility with access modifiers
This chapter assumes you can read basic Apex and have declared a simple class. An access modifier is a keyword that decides which code is allowed to see a class, field, or method. Using the narrowest modifier that works keeps other classes from depending on details you may want to change.
The four modifiers
| Modifier | Who can use the member |
|---|---|
| `private` | Only code inside the same class, including its inner classes |
| `protected` | The same class, plus subclasses that extend it |
| `public` | Any Apex in your namespace (in a normal org, any class in the org) |
| `global` | Any Apex, including code in other namespaces, such as a subscriber org using your managed package |
For members of a class, the default with no modifier is private. Top-level classes are different. You must declare them public or global, with one exception: a test class marked @isTest may be private.
Hiding state behind methods
The usual pattern is to make fields private and expose only the operations callers need. The class below keeps its balance private, so every change has to go through deposit.
public class SavingsAccount {
public class InvalidDepositException extends Exception {}
public static final Decimal MIN_DEPOSIT = 1;
private Decimal balance = 0;
protected String owner;
public SavingsAccount(String owner) {
this.owner = owner;
}
public void deposit(Decimal amount) {
validate(amount);
balance += amount;
}
public Decimal getBalance() {
return balance;
}
private void validate(Decimal amount) {
if (amount == null || amount < MIN_DEPOSIT) {
throw new InvalidDepositException('Deposit must be at least ' + MIN_DEPOSIT);
}
}
}
// Usage
SavingsAccount acct = new SavingsAccount('Ana');
acct.deposit(50);
System.debug(acct.getBalance()); // 50
// acct.balance = 1000; // compile error: balance is not visible
// acct.validate(10); // compile error: validate is privateCallers cannot skip the validation, because validate and balance are not reachable from outside. If you later change how the balance is stored, no calling code breaks.
Choosing a modifier
- Start with
privatefor every field and helper method. - Widen to
publiconly for members that other classes need to call. - Use
protectedfor members that only subclasses should use. It has an effect only when the class can be extended, which a later chapter covers. - Use
globalonly when you build a managed package and need code outside your namespace to call yours.
Rules that interact with other features
- An interface method is declared with no access modifier. The class that implements it must make the method
publicorglobal. - A
globalmethod or variable must be inside aglobalclass. - Inner classes are
privateby default, so mark thempublicif other classes need to use them.InvalidDepositExceptionabove ispublicfor that reason.
Exercise
A class declares Integer retries; with no modifier, and a method void reset() with no modifier. From another class in the same org, can you call reset()? Which modifier should you add if a subclass, but no other class, needs it?
Show answer
No. A member with no modifier is private, so other classes cannot call reset(). To let subclasses use it without exposing it to the rest of the org, declare it protected.