How to Create and Use Constructors in Salesforce Apex Classes

Recently, while working as a Salesforce developer, I created an Apex class constructor for use in Lead Management. In the lead management system, we need to track leads and their details, such as name, email, company, and status. For this, a class representing a Lead was with a constructor to create Lead objects easily.

In this Salesforce tutorial, I will explain the constructors in Salesforce Apex, along with their types and how to create and use them.

What are Constructors in Salesforce Apex?

In Salesforce Apex, a Constructor is a code in the form of a set of instructions invoked when an object is created from the Apex class. Once we create a constructor, we do not need to write a constructor for every class. If a class doesn’t have a user-defined constructor, a default, no-argument constructor with the same visibility as the containing class is generated.

The constructors generally have the same name as the class and do not have a return type.

Sample constructor in Salesforce Apex :

public class MyClass {
    // Constructor
    public MyClass() {
        // Code to execute when an object is created
    }
}

Types of Constructors in Salesforce Apex

In Salesforce Apex, various types of constructors are used to create efficient and flexible Apex classes. Below are the different Apex constructor types used in the Salesforce Apex Classes.

Apex Default Constructor

In Salesforce Apex, a default constructor does not accept any parameters. If no constructors are explicitly defined in a class, Apex automatically provides a default constructor. The default constructor allows for creating an object without passing any arguments.

Below is an example of the Apex Default Constructor:

public class MyClass {
    // Default Constructor
    public MyClass() {
        // This block is executed when an object is created
        System.debug('Default constructor called');
    }
}

This default constructor is a no-argument constructor that allows you to instantiate a class without passing any parameters.

Apex Custom Constructor

We create a Custom Constructor in Apex to modify it according to our requirements. Custom constructors accept parameters, enabling more complex object initialization. Like the default constructor, they do not have a return type. We can define multiple constructors in the same class with different parameter types or numbers of parameters.

Below is an example of an Apex Custom Constructor:

public class AccountManager {
    public String accountName;
    public Decimal annualRevenue;

    // Custom constructor with parameters
    public AccountManager(String accName) {
        this.accountName = accName;
        System.debug('Account created: ' + accountName);
    }
}

Apex Overload Constructor

In Salesforce Apex, the Overload Constructor allows us to add multiple constructors with different parameters to the same class. This constructor allows the creation of instances using various input parameters.

For example, if you have an Employee object and want to pass the Job Role and Salary parameters in the same class, you can use the Overload constructors.

Below is an example of using overloaded constructors in the Apex Class:

Public class Employee {
    public String jobrole { get; set; }
    public Decimal salary { get; set; }

    // constructor
    public Employee(String jobrole) {
        this.jobrole = jobrole;
    }

    // Overloaded constructor
    public Person(String jobrole, Decimal salary) {
        this.jobrole = jobrole;
        this.salary = salary;
    }
}

Apex Static Constructor

In Salesforce Apex, a Static Constructor is used to initialize static variables or perform tasks that need to be executed once for a class, regardless of how many class instances are created. That means there can be only one static constructor per class, mainly used for one-time setup tasks.

The static constructor runs automatically when the class is first referenced, ensuring that static parameters are initialized only once.

The code below is a reference for using the static constructor in the Apex Class.

public class AccClass {
    public static String status;
    
    // Static constructor
    static {
        status = 'Initialized';
        System.debug('Static Constructor Executed');
    }

Apex Controller Constructor

In Salesforce Apex, the Controller Constructor is used in custom controllers and controller extensions for Visualforce pages or Lightning components. This constructor is a method invoked when an instance of the controller class is created. Its primary use is initializing the controller’s state and preparing it to interact with the page.

It also allows us to create new controller functionality to handle user interactions in Visualforce pages, while controller extensions add to or override built-in functionalities.

Below is an example of using the Controller Constructor in the Apex Class.

public class AccountController {
    public List<Account> accounts { get; set; }

    // Constructor
    public AccountController() {
        // Initialize the list of accounts when the controller is created
        accounts = [SELECT Id, Name, Industry FROM Account LIMIT 10];
        System.debug('Constructor executed, accounts loaded.');
    }
}

In the above code, the AccountController() is the constructor method for the AccountController class. It’s called when a Visualforce page using this controller is loaded.
Then, the constructor performs a SOQL query to fetch a list of 10 Account records stored in the accounts list.

Create and Use Constructors in Salesforce Apex Classes

Now, we will create and use the constructors in the Salesforce Apex Class. For that, we will use the above-explained scenario of a lead management system, where we will track leads and their details, such as name, email, company, and status.

For testing and debugging, we will use another Apex class to demonstrate how to add leads and retrieve them.

Create the Apex Class With a Constructor

Create a class LeadManager that includes a default constructor to initialize the initial status of leads. It will also handle lead creation and management.

To create a new class, select File>New>Apex Class. After this, enter the name of the apex class and the code below.

You can modify the fields according to the object and use the correct data type for each field.

public class LeadManager {
    private String initialStatus;

    public LeadManager(String initialStatus) {
        this.initialStatus = initialStatus;
    }

    // add a new lead
    public void addLead(String name, String email, String company) {
        Lead newLead = new Lead();
        newLead.FirstName = name.split(' ')[0];
        newLead.LastName = name.split(' ')[1];
        newLead.Email = email;
        newLead.Company = company;
        newLead.Status = initialStatus; // Use initialStatus from constructor

        insert newLead; 
        System.debug('Lead added to Salesforce: ' + newLead.Id);
    }

    // retrieve all leads
    public List<Lead> getAllLeads() {
        return [SELECT Id, FirstName, LastName, Email, Company, Status FROM Lead];
    }
}
Constructors in Salesforce Apex Class

After entering the above code in the LeadManger class, save it.

Create a class to check the working of LeadManager Class:

Now, we will create a class, Leadtest, to verify the functionality of the LeadManager class.

Enter the code below in the apex class.

public class LeadTest {
    public static void testLeadManagement() {
        // Instance of LeadManager with an initial status
        LeadManager leadManager = new LeadManager('New');

        // Add leads
        leadManager.addLead('Ammy Williamson', 'ay.wiliamson@mail.com', 'Acme Corp');
        leadManager.addLead('Katherine Smith', 'kth.smith@mail.com', 'Tech Inc');

        // Retrieving all leads
        List<Lead> allLeads = leadManager.getAllLeads();
        
        // Debugging lead details
        for (Lead lead : allLeads) {
            System.debug('Lead - Name: ' + lead.FirstName + ' ' + lead.LastName + 
                         ', Email: ' + lead.Email + 
                         ', Company: ' + lead.Company + 
                         ', Status: ' + lead.Status);
        }
    }
}
What are Constructors in Salesforce Apex

To call the LeadTest class for debugging, launch the Apex anonymous window and execute the code below.

LeadTest.testLeadManagement();
Types of Constructors in Salesforce Apex

As we execute the anonymous window code, the execution log’s debug will show the added leads and retrieve the records from the lead object with the fields we defined in the Apex class constructor.

How to create Constructors in Salesforce Apex

As we can see, the lead records we entered in the Leadtest class are inserted into the Lead object, and the constructor class retrieved information on the lead records we defined in the constructor class.

This way, we can use the constructors in Apex classes. In the above class method, we used the default constructor for lead creation and management, and in the same way, you can modify your code and use other constructors in the Apex classes.

Conclusion

In this Salesforce tutorial, we learned about Constructors in Salesforce Apex. We discussed different types of constructors in Apex and their use cases. Then, with the help of a scenario, we learned how to create and use a constructor in the Salesforce Apex class.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.