At times, you'll need to set custom values when constructing objects. This is what we saw in the previous lesson:
public class EmployeeController { Employee newEmployee = new Employee(); }
By itself, newEmployee
isn't very valuable until its name
member variable is initialized. To make sure the name
is initialized when the object is created, we can leverage the constructor. To make this work, the caller, or the piece of code that instantiates the object, will need to provide an argument:
public class EmployeeController { Employee newEmployee = new Employee('Elaine Benes'); }
In order to do that, we have to first update the constructor to accept a String parameter:
public class Employee { String name; Integer startYear; String department; Boolean isCurrentEmployee; public Employee(String initialName) { this.name = initialName; } }
That was a lot, and I don't expect it to make sense to you just yet. Let’s break this down.
Object Instantiation
Similar to the previous lesson, when you declare:
Employee newEmployee = new Employee('Elaine Benes');
you are creating an instance of the Employee class. This process is known as object instantiation. The Employee class defines the blueprint for creating Employee objects, and newEmployee
is now a proxy for accessing the member variables of the new object and invoking it's methods. But instead of a proxy, we just call it a variable.
Parameters & Constructors
A constructor may accept parameters in order to initialize the object's member variables. In this case, the constructor of the Employee class takes a single String parameter: initialName
and assigns it to the name
member variable of the newEmployee
object.
When the String literal 'Elaine Benes' is passed to the constructor:
new Employee('Elaine Benes');
the string 'Elaine Benes' is assigned to the parameter initialName
within the scope of the constructor. This means initialName
holds the value 'Elaine Benes' during the execution of the constructor.
The line this.name = initialName;
within the constructor assigns the value of initialName
to the name field of the Employee object. Therefore, the name field of newEmployee
will have the value 'Elaine Benes'.
There’s a catch
When we create argument constructors, Apex no longer automatically provides a no-argument constructor. We’ll have to explicitly create our own if we want one. A class defined like this would compile fine.
public class Employee { String name; Integer startYear; String department; Boolean isCurrentEmployee; public Employee(String initialName) { this.name = initialName; } }
But if we initialized it with a no-arguments constructor:
public class EmployeeController { Employee newEmp = new Employee(); //this wouldn’t compile! // Employee newEmp = new Employe(‘SomeString’); Need to call it like this instead }
We’d receive a compilation error saying Constructor not defined: [Employee].<Constructor>()
.