The Apex Master Class

What Is a Constructor in Apex? (Master Class Ep. 13)

4 min read

Subscribe on YouTube

What Is A Constructor?

A constructor is a special method that runs automatically the moment your class gets created. You don’t call it. It just fires.

It does two jobs:

1. It lets you create the same class in different flavours.
2. It sets up whatever your class needs before anything else runs.

Sticking with the computer from last episode: sometimes you want that computer built as a server. Sometimes you want it built as a gaming PC. Same blueprint, different setup. That’s what constructors are for.


What One Looks Like

Constructors look like methods with two odd things about them: the name is exactly the class name, and there’s no return type. Not even void.

Apex
public class Computer
{
    private String computerType;
    private Integer ramInGb;

    //This is the constructor. Same name as the class, no return type.
    public Computer(String typeOfComputer, Integer ram)
    {
        computerType = typeOfComputer;
        ramInGb      = ram;
    }

    public void describeMe()
    {
        System.debug('I am a ' + computerType + ' with ' + ramInGb + 'GB of RAM');
    }
}

Now the same class can come out two completely different ways:

Code
Computer server    = new Computer('Server', 128);
Computer gamingRig = new Computer('Gaming PC', 32);

server.describeMe();      //I am a Server with 128GB of RAM
gamingRig.describeMe();   //I am a Gaming PC with 32GB of RAM

Remember the new keyword from episode 10? That’s what runs the constructor. Every time you write new Something(...), a constructor fires.


The Default Constructor You Never Wrote

Hang on though. Back in episode 7 we made a MappingService class with no constructor anywhere in it, and then happily wrote new MappingService(). How did that work?

Because if you don’t write a constructor, Apex quietly writes an empty one for you. It takes no parameters and does nothing. You never see it, it’s just there.

Here’s the trap, and it’s a good one: the moment you write your own constructor, that free one disappears.

Code
//Given the Computer class above, this now BLOWS UP:
Computer myPc = new Computer();

Apex will tell you there’s no constructor matching that signature, which is a fun error to hit at 5pm when you swore you didn’t change anything relevant. You defined a constructor taking two parameters, so that’s the only way in now.

Unless, of course, you define more than one.


You Can Have Several

A class can have as many constructors as you like, as long as each takes a different set of parameters. This is called overloading, and Apex works out which one you meant from what you pass in.

Apex
public class Computer
{
    private String computerType;
    private Integer ramInGb;

    //No arguments? Fine, have some sensible defaults.
    public Computer()
    {
        computerType = 'Desktop';
        ramInGb      = 16;
    }

    //Just a type? We'll fill in the rest.
    public Computer(String typeOfComputer)
    {
        computerType = typeOfComputer;
        ramInGb      = 16;
    }

    //Tell us everything.
    public Computer(String typeOfComputer, Integer ram)
    {
        computerType = typeOfComputer;
        ramInGb      = ram;
    }
}

All three of these now work, and each produces a differently configured computer:

Code
Computer basic  = new Computer();
Computer server = new Computer('Server');
Computer beast  = new Computer('Gaming PC', 64);

The Other Job: Setting Things Up

The second use is less flashy but you’ll lean on it constantly. Sometimes your class depends on other things existing before it can do anything useful, and the constructor is where you get all that sorted.

Apex
public class OpportunityService
{
    private List<Opportunity> opportunities;
    private EmailService emailer;

    public OpportunityService(Set<Id> opportunityIds)
    {
        //Grab everything we need, once, up front
        opportunities = [SELECT Id, Name, Amount, StageName
                        FROM Opportunity
                        WHERE Id IN :opportunityIds];

        emailer = new EmailService();
    }
}

Now every method in this class can rely on opportunities and emailer already being ready, instead of each one defensively checking and re-querying. One query, done once, at construction.

Don’t worry about the SOQL syntax, we cover that properly in episode 32.

One word of warning though, and I mean this: keep constructors light. It’s very tempting to cram loads of work in there because “it needs doing anyway.” Resist. A constructor doing ten queries and calling three web services is miserable to test and produces baffling failures. Set up state, then stop.


What’s Next

Constructors: same name as the class, no return type, run automatically on new. You get a free empty one until you write your own. You can have several with different parameters. Keep them light.

Full details in the Apex Developer Guide here.

I’ve now used the word “instantiate” several times while assuming everyone knows what it means, so in the next episode we’ll slow down and cover exactly what happens when you create an instance of a class.

See you next time!


Get Coding With The Force Merch!!

We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.

Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!


Check Out More Coding With The Force Stuff!

If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!

Youtube
Patreon
Github
Facebook
Twitter
Instagram


Salesforce Development Books I Recommend

Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture