Sub topic 2
Controlling visibility with access modifiers
This chapter assumes you can read basic Apex syntax and know what a class, a field, and a method are. You should also know that Apex code runs inside Salesforce transactions. Here you will learn which parts of a class other code can see, and how to choose the narrowest visibility that still works.
What an access modifier does
An access modifier is a keyword placed at the start of a declaration. It decides which other code can use that class, variable, property, method, or constructor. Apex has four of them: private, protected, public, and global.
Visibility is a design tool. A field that nothing outside the class can touch is a field you can rename, retype, or delete without breaking other code. Every member you expose becomes something you must keep working.
The four modifiers
| Modifier | Who can use the member |
|---|---|
| `private` | Only code inside the class that defines it, including that class's inner classes. |
| `protected` | The defining class, its inner classes, and classes that extend it. |
| `public` | Any Apex in your namespace. In an org without a managed package namespace, that means any Apex in the org. |
| `global` | Any Apex anywhere, including code in other namespaces. Used for APIs that a managed package exposes. |
The modifiers widen in this order:
Defaults and where each modifier is allowed
If you leave the modifier off a variable, property, or method, Apex treats it as private. Writing the modifier explicitly is still better, because a reader then knows the choice was deliberate.
The rules differ by kind of declaration:
- A top-level class must be declared
publicorglobal. The exception is a test class marked@IsTest, which may beprivate. - An inner class has no such restriction and is
privateby default. - Methods and variables can use any of the four modifiers.
- A
globalmethod or variable requires its class to beglobal. Aglobalclass can still containpublicandprivatemembers, but code outside your namespace sees only theglobalones.
Interface methods are the one place where you write no modifier at all. The interface's own access level applies to them. When a class implements the interface, its implementing methods must be public or global.
A worked example
The Wallet class below uses three of the four modifiers, and a subclass shows what protected allows.
public virtual class Wallet {
private Decimal balance;
protected String ownerName;
public Integer transactionCount { get; private set; }
public Wallet(String ownerName) {
this.ownerName = ownerName;
this.balance = 0;
this.transactionCount = 0;
}
public void deposit(Decimal amount) {
if (amount <= 0) {
throw new IllegalArgumentException('Amount must be positive');
}
balance += amount;
transactionCount++;
audit('deposit', amount);
}
public Decimal getBalance() {
return balance;
}
protected virtual void audit(String action, Decimal amount) {
System.debug(ownerName + ' ' + action + ' ' + amount);
}
}public class AuditedWallet extends Wallet {
public AuditedWallet(String ownerName) {
super(ownerName);
}
protected override void audit(String action, Decimal amount) {
// ownerName is protected, so the subclass can read it.
System.debug('AUDIT [' + ownerName + '] ' + action + ' ' + amount);
// balance is private to Wallet, so this line would not compile:
// System.debug(balance);
}
}Wallet w = new AuditedWallet('Ana');
w.deposit(50);
System.debug(w.getBalance()); // 50
System.debug(w.transactionCount); // 1
// w.balance = 10; // compile error: balance is private
// w.transactionCount = 99; // compile error: the setter is private
// w.audit('x', 1); // compile error: audit is protectedEach choice has a reason:
balanceisprivate. Onlydepositchanges it, so the "amount must be positive" rule cannot be bypassed.transactionCountis a property with apublicgetter and aprivatesetter. Outside code can read it but cannot change it.ownerNameisprotected, so subclasses can use it in their own logic while unrelated classes cannot.auditisprotectedandvirtual. It is a hook for subclasses, not part of the public API.getBalance()ispublic. It gives read access without write access.
Read-only properties with split access
An Apex property can give its getter and setter different modifiers. The accessor with the narrower modifier is the one you restrict:
public String status { get; private set; }
public Integer retries { protected get; set; }The first form is the most common. It publishes a value but keeps the right to change it inside the class. An explicit modifier on an accessor can only narrow the property's visibility, never widen it.
Public versus global
For code inside one org, public is almost always the right choice. global matters when you build a managed package.
- Global members become part of your package's published API. After release you can't remove or change them freely, because subscribers may depend on them.
- Public members stay internal. You can refactor them in later package versions.
- Apex web service methods (
webservicekeyword) and some REST and email handler entry points require aglobalclass.
In an ordinary org, use public unless a platform feature tells you global is required.
Testing private members with @TestVisible
Tests often need to call private members. Making them public just for tests widens your API for no production benefit. The @TestVisible annotation solves this: it lets test classes see a private or protected member, and nothing else changes.
public class Pricing {
@TestVisible
private static Decimal taxRate() {
return 0.2;
}
public static Decimal withTax(Decimal net) {
return net + (net * taxRate());
}
}@IsTest
private class PricingTest {
@IsTest
static void taxRateIsTwentyPercent() {
Assert.areEqual(0.2, Pricing.taxRate());
}
@IsTest
static void withTaxAddsTax() {
Assert.areEqual(120, Pricing.withTax(100));
}
}Common mistakes
- Making everything
public. It compiles, but every public member is a commitment. Start withprivateand widen only when another class actually needs access. - Expecting
privateto mean "private to the object". In Apex,privateis scoped to the class. Two instances of the same class can read each other's private fields. - Using
globalby habit. Besides committing you to the API, aglobalclass forces any of its members that other namespaces use to beglobaltoo. - Forgetting that
protectedis notpublic. A caller holding aWalletvariable cannot callaudit, even though a subclass can override it. - Giving a class a public field with no validation. A public field lets any caller bypass your rules. Prefer a private field with a method, or a property with a private setter.
Choosing a modifier
Work down this list for each member and stop at the first that fits:
- Does only this class need it? Use
private. - Do only subclasses need it, as with a hook method or shared field? Use
protected. - Do other classes in the same namespace or org need it? Use
public. - Must code in other namespaces call it, as in a managed package API? Use
global.
Exercise
A class OrderService has a field Decimal discountRate that only its own methods change, but a ReportBuilder class in the same org must read it. Which declaration is best, and why?
Show answer
Declare public Decimal discountRate { get; private set; }. The public getter lets ReportBuilder read the value. The private setter keeps all changes inside OrderService, so it can enforce its own rules. public on the field itself would let any class overwrite it, and global would be needed only for code in other namespaces.
Exercise
A subclass SpecialWallet extends Wallet tries to run System.debug(balance);, and the code does not compile. Name two changes that would fix it, and say which is better.
Show answer
Either change balance in Wallet from private to protected, or add a public or protected method such as getBalance() and call that from the subclass. Calling the method is better, because the field stays private and Wallet keeps control of how its balance is read and changed.