Access Modifiers
By the end of this lesson, you'll be able to:
- Explain what public, private, and protected control
- Choose an appropriate access modifier for a field or method
- Recognize private as the safer default for internal implementation details
Prerequisites: "Properties: get and set"
The main three: private, public, protected
public class BankAccount {
private Decimal balance; // only visible inside this class
public Decimal getBalance() { // visible to any code that has a BankAccount
return balance;
}
}
private— visible only inside the same class. This is the safest default for internal details.public— visible to any code, anywhere in the org.protected— visible inside the class and any class that extends it (covered in a later module on inheritance).
Why hide balance behind private?
BankAccount account = new BankAccount();
// account.balance = 1000000; // compile error — balance is private
System.debug(account.getBalance()); // fine — getBalance() is public
If balance were public, any code anywhere could set it directly to anything, bypassing whatever business rules should govern it (like "never allow a negative balance"). Making it private and exposing controlled access through a public method — a pattern called encapsulation — forces every change to go through logic you control. A later module covers this principle in depth.
A real business example: Legal (Case File Access)
public class CaseFile {
private String confidentialNotes;
public String caseNumber { get; set; }
public String getSummaryForClient() {
return 'Case ' + caseNumber + ': in progress.';
}
}
confidentialNotes stays private — internal only — while caseNumber and a client-safe summary method are public. This mirrors a real access-control need: some data (like privileged legal notes) should never be exposed outside the class that manages it.
A sensible default
When unsure, start with private and only widen access (to public or protected) once something outside the class genuinely needs it. It's far easier to loosen access later than to discover — after other code already depends on it — that a field should never have been exposed.
Exercise
Rewrite the Book class so pageCount is private, with a public method getPageCount() that returns it.
Show hint
private Integer pageCount; public Integer getPageCount() { return pageCount; }
Access Modifiers Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Access modifiers control who is allowed to see or use a field, method, or class — choosing the most restrictive one that still works is a core habit of writing maintainable code.