Instantiating sObjects
Not Started

sObjects don't exist in isolation. Their full potential is realized when paired with a trigger, SOQL, or a DML statement. Trailhead covers those topics well, so they're yet to be included in Camp Apex.

sObjects in Apex reference a Salesforce record in the database. For that to happen, we must create a variable of a particular sObject type. Like this:

Account acc = new Account();

What we've done here should look familiar.

Computer Science Version:
On the right-hand side, the new operator instantiates the object by allocating memory. It then invokes the object's constructor Account() which initializes the object. Finally, it returns a reference to the object's memory address. On the left-hand side, we've declared a variable named acc of the datatype Account that accepts the reference provided by the new operator.

Simplified Version:
On the left-hand side of the equals sign, we've declared a variable named acc of the datatype Account. On the right-hand side, we've created a new empty Account object using the new operator.

When the line executes, we have an empty Account object at our disposal. But what good is an empty object? It's no good!

We can set the fields of an sObject by passing them into the constructor. Say we wanted to create an Account with the name Stark Industries.

Account acc = new Account(Name = 'Stark Industries');

Easy! With a comma-separated list, you can set other fields too:

Account acc = new Account(Name='Stark Industries', NumberOfEmployees=1200, customField__c = true);

This works for all sObject types:

Opportunity opp = new Opportunity(StageName = 'Closed Won'); CustomObject__c co = new CustomObject__c(Name = 'It works!', CustomField__c = 10);

Now, a caveat here: the field must exist in the Salesforce org. If the field doesn't exist, you wont be able to compile your code:

Opportunity opp = new Opportunity(ImaginaryFieldThatDoesntExist__c = 'A Silly Mistake');

Field does not exist: ImaginaryFieldThatDoesntExist__c on Opportunity. The same goes for referencing a sObject API name that doesn't exist:

ObjectThatDoesntExist__c obj = new ObjectThatDoesntExist__c();

Would fail to compile with the following message: Invalid type: ObjectThatDoesntExist__c.

Typically, once we instantiate sObject records in Apex and set the desired fields, we'll use a DML call to insert the record in the database.

Account monstersAccount = new Account(Name='Monsters Inc'); insert monstersAccount;

monstersAccount now has an Id associated with it. If we looked in the Salesforce UI, we'd see this new Account. I'd encourage you to take the Trailhead module for DML after you're done with this course.

Challenge

Create a variable named newContact of the type Contact. Use the new operator to create a Contact object and set the LastName field to Smith using the constructor.