Specifying private
on the employeeId
member variable has created a problem.
We not only prevented the outside class from editing employeeId
, we also prevented the outside class from reading employeeId
. Accessing this member variable via the dot operator will yield a compilation error:
public class EmployeeController { Employee newEmp = new Employee(); String empId = newEmp.employeeId; // Compilation Failure: Variable is not visible: Employee.employeeId }
The sky is falling! Let’s modify the Employee
class so that employeeId
can be read but not set by outside classes. How? With Apex Properties, baby!
There are a few different properties out there - for now, we’re just going to talk about automatic properties. You can read about the others here if you’re up for it.
Properties automatically execute when a member variable is set or retrieved via accessors. When variables are set using the dot operator, they’re implicitly calling the set
accessor. When values are retrieved using the dot operator, they’re implicitly calling the get
accessor.
But how can we use property accessors to solve our problem? Well, we can use access modifiers on property accessors. 🤯 Yeah, you read that right.
Rewriting Employee
would look like this:
public class Employee { public String employeeId { get; private set; } public Employee(){ this.employeeId = // fancy logic that sets employee id } }
The accessor must be more restrictive than the member variable itself. If it's not, you'll receive a compilation error saying Cannot declare public accessor on private property
. In our case, employeeId
will be public
for get
(because the access modifier on employeeId
is inherited) and it will be private
for set
.
This solves our problem! Now, EmployeeController
can read employeeId
from an Employee object but cannot set it.
public class EmployeeController { Employee newEmp = new Employee(); String empId = newEmp.employeeId; // this works now! // newEmp.employeeId = ‘INVALID ID skdhgkjsdf’; This would still cause a compile error (which is what we want) }