Private Access Modifiers
Not Started

In Apex, we can declare variables with the following access modifiers: public, private, protected, and global. Checkout Salesforce’s Apex docs for a full breakdown.

When code refers to an object, the access modifiers determine which member variables from that object we can use. When we define a class, we need to decide which access modifier each member variable should have.

By default, member variables are implicitly private. This specifies that a member variable is only accessible by its own Apex class. It’s a good rule of thumb to define member variables as private to begin with and open it up later if the need arises.

The idea behind this stems from Encapuslation, the idea that software systems should limit access to their internals so that the internals can change without impacting callers or clients referring to the object. This is a step towards flexible software and expressing intent with our code.

Referring back to Employee, we left out a key member variable, the employee’s id number. The constructor should be responsible for creating and setting the Employee ID because there are certain rules the company has put in place for the ID number.

public class Employee { public String employeeId; public Employee(){ this.employeeId = // logic that creates the employee id based on specific rules } }

If left public, any class that instantiates Employee could alter the employeeId in a way that would violate the specific rules:

public class EmployeeController { Employee newEmployee = new Employee(); newEmployee.employeeId = 'Random Invalid Employee Id'; // now we have an invalid employee id }

We don’t want this. Instead, we’ll declare employeeId as private so only the Employee class can set it. This ensures that the rules are always followed when the member variable is set.

public class Employee { private String employeeId; public Employee(){ this.employeeId = // logic that creates the employee id based on specific rules } }

The following code would no longer compile and result in the following error: Variable is not visible: Employee.employeeId:

public class EmployeeController { Employee newEmployee = new Employee(); newEmployee.employeeId = 'Random Invalid Employee Id'; }

employeeId is now tamper-proof.

Challenge

Create a class named Student. Declare a private member variable named studentId of type String. Using the constructor, set the member variable to the String literal s-000123.