What good is all this data if we can’t access it? Honestly, you’re right. Now that we know how to set member variables via the constructor, let’s explore how we can read member variables.
Let’s continue with a simplified version of the Employee
class:
// Saved in Employee.cls public class Employee { public String firstName; public String lastName; public Employee(String firstName, String lastName){ this.firstName = firstName; this.lastName = lastName; } }
Which is called and instantiated from another class stored in a separate file:
// Saved in EmployeeController.cls public class EmployeeController { Employee newEmployee = new Employee('George', 'Costanza'); }
The public
keyword preceding firstName
and lastName
in the Employee
class is an access modifier. It gives other classes (like EmployeeController
) access to the member variables of Employee
. Previously, there was no access modifier. If one is not declared, Apex uses an implicit private access modifier. Meaning the member variables can only be accessed from within the class.
We’ll access member variables via the dot operator .
. The dot operator is used to reach in and access the contents of a class. You’ve already encountered this operator when learning about the this
keyword; we just never made a big deal about it.
// Saved in EmployeeController.cls public class EmployeeController { Employee newEmployee = new Employee('George', 'Costanza'); String firstNameFromObject = newEmployee.firstName; // firstNameFromObject is now set to ‘George’ String lastNameFromObject = newEmployee.lastName; // lastNameFromObject is now set to ‘Costanza’ }
We’ve come full circle! The public
keyword on member variables can be a double-edged sword. Not only can we read the member variables, but we can also edit them. We’d be able to override firstName
using the dot operator like this:
// Saved in EmployeeController.cls public class EmployeeController { Employee newEmployee = new Employee('George', 'Costanza'); String firstNameFromObject = newEmployee.firstName; // firstNameFromObject is now set to ‘George’ newEmployee.lastName = 'Benes'; // the newEmployee object now represents 'George Benes' String lastNameFromObject = newEmployee.lastName; // lastNameFromObject is now set to 'Benes' }