Objects & No Argument Constructors
Not Started

This Employee class isn’t very helpful on its own:

public class Employee { String name; Integer startYear; String department; Boolean isCurrentEmployee; }

Remember, a class is a blueprint, or a model, for creating objects. This class does not represent a specific Employee, instead, it tells Apex what an Employee should look like and how it’s data should be structured.

To represent a specific Employee, we need to create an object by instantiating our class with the new keyword:

Employee newEmployee = new Employee();

Let’s break this code down into the left-hand side and right-hand side of the equals sign.

On the left-hand side, a new variable named newEmployee is declared with the datatypeEmployee. On the right hand, the Employee class is instantiated and a new Employee object is created. We can now reference this object using the newEmployee variable.

This is the first time we’re seeing the open and close parenthesis () syntax. When a class is instantiated via new, its constructor is automatically invoked. The constructor is a special piece of code that defines how an object should be built. This is where we can pass in default values to an object or run specified logic upon creation.

Now, where is our Employee constructor? Apex implicitly provides a default no-argument constructor for us. Apex developers don’t need to explicitly declare one if they don’t need one. If you were to declare a constructor, it would look like this:

public class Employee { String name; Integer startYear; String department; Boolean isCurrentEmployee; public Employee() { // optional constructor code that runs initialization behavior } }

The constructor must have the same name as its class. The public keyword makes the constructor accessible to other classes.

Let’s say every time an object is instantiated, you want to set the startYear to the current year. We can add that logic in our constructor to guarantee it happens:

public class Employee { String name; Integer startYear; String department; Boolean isCurrentEmployee; public Employee() { this.startYear = 2023; } }

The this keyword is a reference variable. It refers to the current object - the object whose constructor is being called. this lets us refer to any member variable of the current object from within the constructor. Now when we create the object:

Employee newEmployee = new Employee();

The code snippet this.startYear = 2023; will automatically run and set the newEmployee’s startYear to the current year. We’ll prove it to you in the next few lessons.

Challenge

Define a class named Teacher. Declare two member variables named firstName and lastName both of type String. Declare an Integer member variable named yearsOfExperience and a Boolean named isActiveTeacher. Create a constructor and use it to set the isActiveTeacher member variable to true.