Sub topic 1
Declaring an Apex Class
Prerequisites
This chapter assumes you already have the following:
- Basic Apex syntax: variables, data types,
ifandforstatements. - Familiarity with collections such as
ListandMap. - Awareness that Apex runs on Salesforce inside transactions.
- Basic object-oriented ideas: an object has data and behavior, and a method is a named piece of behavior.
You do not need to know interfaces, inheritance, or static members yet. Later chapters cover them. Here you learn the shape of a class and the rules for declaring one.
What a class is in Apex
An Apex class is a template that describes data (fields) and behavior (methods). You create objects from the template with the new keyword. Each object is called an instance of the class.
Apex is a strongly typed, compiled language that runs on the Salesforce platform. You do not compile locally. When you save a class, Salesforce compiles it on the server and stores it in your org. If compilation fails, the save fails, and the class is not stored.
Classes are the main building block of Apex. Triggers, batch jobs, REST services, and test code all call into classes or are classes.
The anatomy of a declaration
A class declaration has a header and a body. The header says who can see the class and what kind of class it is. The body, between braces, holds the members.
public with sharing class Greeter {
public String name = 'World';
public String greet() {
return 'Hello, ' + name + '!';
}
}This header has four parts, in this order:
| Part | Example | Required for a top-level class? |
|---|---|---|
| Access modifier | `public` or `global` | Yes |
| Sharing or kind keyword | `with sharing`, `virtual`, `abstract` | No |
| The word `class` | `class` | Yes |
| Name | `Greeter` | Yes |
After the name you can add extends and implements clauses. Later chapters cover those. The sharing keywords also get their own chapter. For now, treat with sharing as an optional keyword that controls record-level security.
Naming rules
- Names start with a letter and can contain letters, digits, and underscores.
- Apex is case-insensitive, so
Greeterandgreeterare the same name. Pick the capitalization you want and use it everywhere. The convention is UpperCamelCase for classes and lowerCamelCase for methods and variables. - A class name must be unique within your namespace.
- Avoid names that clash with system types such as
Account,List, orDatabase. Naming a classAccountshadows the standard type in confusing ways.
Where class code lives
Each top-level class is stored as its own file in source-driven development. With Salesforce DX, a class named Greeter is two files in force-app/main/default/classes/:
Greeter.clsholds the Apex source.Greeter.cls-meta.xmlholds the metadata.
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>61.0</apiVersion>
<status>Active</status>
</ApexClass>The apiVersion pins the class to a platform release. Salesforce keeps older behavior for older versions, so an old class does not break when the platform upgrades. The status can be Active or Deleted.
You can also create classes in the Developer Console (File > New > Apex Class) or in Setup under Apex Classes. All three routes produce the same stored class.
The rule is one top-level class per file. The file name must match the class name.
flowchart TDThe diagram below shows how one file maps to one class and what the class can contain.
What goes in the class body
The body can contain these kinds of members:
- Fields, also called member variables, hold data.
- Methods hold behavior.
- Constructors run when you create an instance.
- Initialization blocks run setup code.
- Inner classes are classes declared inside another class.
- Properties are fields with
getandsetaccessors.
Statements cannot sit directly in the body. Code such as System.debug('hi'); must be inside a method, constructor, or block.
Here is a slightly larger class that uses several member kinds.
public class Invoice {
public String customer;
public Decimal amount = 0;
public Decimal withTax(Decimal rate) {
return amount + (amount * rate / 100);
}
public String summary() {
return customer + ': ' + withTax(20);
}
}Methods can call each other and read fields without any prefix. summary() calls withTax() directly.
Creating and using an object
You declare a variable of the class type and assign a new instance to it. You then reach fields and methods with a dot.
Invoice inv = new Invoice();
inv.customer = 'Acme';
inv.amount = 200;
System.debug(inv.summary()); // Acme: 240You can run this in the Developer Console under Debug > Open Execute Anonymous Apex. Tick "Open Log" and read the USER_DEBUG line.
The new Invoice() call uses the default constructor. If you declare no constructor, Apex supplies a public one with no arguments. If you declare any constructor yourself, Apex no longer adds the default one, so new Invoice() stops compiling unless you also write a no-argument constructor. The next chapters cover constructors in detail.
A variable of a class type holds a reference. Declaring the variable does not create an object.
Invoice missing;
System.debug(missing == null); // true
// missing.summary(); // would throw System.NullPointerExceptionTwo variables can point to the same object. Assigning one to the other copies the reference, not the object.
Invoice first = new Invoice();
Invoice second = first;
second.customer = 'Globex';
System.debug(first.customer); // GlobexDefault visibility
Members you declare without an access modifier are private. Only code inside the same class can use them. This is stricter than in some other languages, and it is a common source of compile errors.
public class Box {
Integer size = 3; // private by default
public Integer width = 4; // visible to other classes
}Code in another class that writes new Box().size fails to compile. The next chapter covers private, public, and global in full.
Common errors when declaring classes
| Symptom | Likely cause | Fix |
|---|---|---|
| Save fails with a compile error on the header | Missing `public` or `global` on a top-level class | Add an access modifier |
| `new MyClass()` fails after you add a constructor | Declaring a constructor removes the implicit no-argument one | Add an explicit no-argument constructor |
| Field not visible from another class | Members are private by default | Mark the field `public` |
| `System.NullPointerException` | Variable declared but never assigned with `new` | Create the instance before using it |
| Two classes with the same name in different casing | Apex names are case-insensitive | Use one unique name |
Putting it together
A class declaration is a header plus a body. The header sets visibility and kind. The body holds fields and methods. You create objects with new, and each object gets its own copy of the instance fields. The later chapters build on this: they tighten who can see what, add constructors, and then contrast per-object state with per-class state.
Exercise
Why does class Helper { public Integer value; } fail to save as a top-level class, and what is the smallest change that fixes it?
Show answer
A top-level class must have an access modifier, either public or global. Adding public in front of class fixes it: public class Helper { public Integer value; }.
Exercise
Given public class Tally { public Integer total = 0; public void add(Integer n) { total += n; } }, what does this code print?
Tally a = new Tally();
Tally b = a;
b.add(5);
System.debug(a.total);
Show answer
It prints 5. The assignment Tally b = a; copies the reference, so a and b point to the same object. Calling b.add(5) changes the shared object, and a.total reads that change.
Exercise
You add the constructor public Invoice(String customer) { this.customer = customer; } to the Invoice class. Why does new Invoice() now fail to compile, and how do you restore it?
Show answer
Apex only provides the implicit no-argument constructor when the class declares no constructors. Once you declare one, you must write the no-argument constructor yourself, for example public Invoice() { }.