The Apex Master Class

How to Instantiate a Class in Apex (Master Class Ep. 14)

3 min read

Subscribe on YouTube

What Is Class Instantiation?

We now know what a class is, what a method is, and what a constructor is. Which is lovely, and completely useless until you can actually use the things you’ve built.

That’s what instantiation is. You take the class you wrote, start it up, and get it running so you can call its methods.

Back to the blueprint idea one more time, because it’s the cleanest way to see it. Your class is the blueprint for the toaster. Instantiating it is actually building a toaster from that blueprint. The blueprint can’t make toast. The toaster can.

The thing you get back is called an instance or an object.


Doing It

You’ve already seen this. It’s the new keyword:

Code
Computer myComputer = new Computer('Gaming PC', 32);

Reading that left to right:

Computer – the type of the variable. We’re holding a Computer.
myComputer – whatever we want to call it.
new – the magic word. Go build one.
Computer('Gaming PC', 32) – which constructor to run, and what to feed it.

Now myComputer holds a live, working instance and you can call anything on it:

Code
myComputer.describeMe();
myComputer.startUp();

That dot is doing the work. It means “on this specific instance, run this method.”


Every Instance Is Its Own Thing

This is the bit worth actually understanding, because it’s where the whole idea clicks.

You can build as many instances as you want from one class, and each one keeps its own state. They don’t share anything. They don’t know about each other.

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

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

One blueprint, three machines, three completely separate sets of values. Change the RAM on laptop and server couldn’t care less.

Three toasters off the same production line. Burn the toast in one, the other two are fine.


The Throwaway Version

If you only need the instance for one call, you don’t have to bother naming it:

Code
//The long way
MappingService mapper = new MappingService();
mapper.calculateDistance();

//Same thing, one line
new MappingService().calculateDistance();

That second form is what I’ve been quietly sneaking into the anonymous Apex snippets for the last few episodes without explaining it. Now you know.

Use it when you genuinely only need the object once. If you’re going to call three methods on it, name the variable, otherwise you’re building three separate objects for no reason.


Instantiated But Empty Is Not The Same As Null

Quick but genuinely useful distinction:

Code
//Declared, but nothing was built. This is null.
Computer computerOne;

//Declared AND built. This is a real object.
Computer computerTwo = new Computer();

computerOne.describeMe();   //BOOM. NullPointerException.
computerTwo.describeMe();   //works fine

The first line makes a variable that could hold a Computer but currently holds nothing at all. Call a method on it and Apex throws System.NullPointerException: Attempt to de-reference a null object, which is comfortably the error you will see most often in your Salesforce career.

And that’s all it ever means: you tried to use something that was never actually built. When you hit it, go find the thing you forgot to new up.


What’s Next

Instantiation: new turns a blueprint into a working object, each instance has its own state, and forgetting to do it is where NullPointerExceptions come from.

In the next episode we cover operators, which is where we finally explain why = and == are not the same thing and why mixing them up ruins your afternoon.

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