Sub topic 5
Static variables and methods: state per class
This chapter assumes you can write basic Apex (variables, control flow, collections) and that you know the difference between a class and an object. It also assumes you know that Apex code runs inside a Salesforce transaction. You should already have seen instance fields and constructors. Here the focus is on members that belong to the class itself.
What static means
An instance member exists once for every object you create with new. A static member exists once for the class, no matter how many objects exist. You can use a static member without creating any object.
You mark a member static with the static keyword. You then reach it through the class name.
public class Visitor {
public static Integer totalVisitors = 0;
public String name;
public Visitor(String name) {
this.name = name;
totalVisitors++;
}
}
// Usage (anonymous Apex)
Visitor a = new Visitor('Ana');
Visitor b = new Visitor('Bo');
System.debug(Visitor.totalVisitors); // 2
System.debug(a.name); // Ana
System.debug(b.name); // BoEach Visitor has its own name. There is one totalVisitors. Both constructors increment the same variable, so the class name Visitor is the only handle you need to read it.
Static variables
A static variable holds one value for the class. Any code that can see it reads and writes the same storage. Visibility follows the access modifier, so a private static variable is shared by all instances and static methods of that class but is invisible outside it.
Static variables are useful for three kinds of data:
- Counters and flags that track what has happened so far.
- Caches that avoid repeating an expensive query or calculation.
- Values shared by several methods of the same class, such as a lookup map.
Because the storage is shared, one object can change what every other object sees. Treat a public static variable like a global variable. Anything can change it, and you may not know who did. Prefer private static plus a method, so the class controls how the value changes.
public class VisitorLog {
private static Integer total = 0;
public static void record() {
total++;
}
public static Integer getTotal() {
return total;
}
}Callers use VisitorLog.record() and VisitorLog.getTotal(). They cannot set total to an arbitrary value.
Static methods
A static method belongs to the class and runs without an object. You call it with ClassName.methodName(). It has no this, because there is no current object.
There are two common uses.
Utility methods take their input as parameters and return a result. They need no object state.
public class StringUtil {
public static String initials(String fullName) {
if (String.isBlank(fullName)) {
return '';
}
List<String> parts = fullName.trim().split('\\s+');
String result = '';
for (String part : parts) {
result += part.substring(0, 1).toUpperCase();
}
return result;
}
}
// Usage
System.debug(StringUtil.initials('ada lovelace')); // ALFactory methods create objects and give the construction a meaningful name. The Counter.createStartingAt(5) method from this tutorial's running example is one. A factory method can also validate its input, return a cached object, or pick one of several constructors.
public class Money {
public final Decimal amount;
public final String currencyCode;
private Money(Decimal amount, String currencyCode) {
this.amount = amount;
this.currencyCode = currencyCode;
}
public static Money usd(Decimal amount) {
return new Money(amount, 'USD');
}
public static Money eur(Decimal amount) {
return new Money(amount, 'EUR');
}
}
// Usage
Money price = Money.usd(19.99);
System.debug(price.currencyCode); // USDThe constructor is private, so the only way to build a Money from outside is through the named static methods. That is a deliberate use of static members to control construction.
What static code can reach
A static method can use static members and its own parameters and local variables. It cannot use instance fields or instance methods directly, because it does not know which object you mean. Apex rejects this at compile time.
public class Broken {
private Integer count = 0;
public static void bump() {
count++; // Compile error: instance variable used in a static context
}
}An instance method has no such limit. It can read and write static members freely, which is how the Visitor constructor updates totalVisitors. If a static method needs instance data, pass the object in as a parameter or create one inside the method.
The chapter on static versus instance rules covers this table in full. For now, remember that access runs one way: instance code sees static members, and static code does not see instance members.
A cache with a static variable
The most practical use of a static variable in Salesforce code is a per-transaction cache. This class queries each account at most once, however many times other code asks for it.
public class AccountCache {
private static Map<Id, Account> cache = new Map<Id, Account>();
public static Account getById(Id accountId) {
if (accountId == null) {
return null;
}
if (!cache.containsKey(accountId)) {
List<Account> found = [
SELECT Id, Name, Industry
FROM Account
WHERE Id = :accountId
LIMIT 1
];
if (found.isEmpty()) {
return null;
}
cache.put(accountId, found[0]);
}
return cache.get(accountId);
}
}This pattern saves SOQL queries, which count against governor limits. It also has a cost. If another piece of code updates the account after it was cached, the cached copy is stale. Only cache data that will not change within the transaction, or clear the entry when you change the record.
How long static values last
Static values last for the current transaction, not for the whole org or for the user session. When the transaction ends, the values are discarded. The next transaction starts with every static variable at its initial value.
This has practical consequences:
- A static counter does not count across users or across requests. Two users saving records at the same time each see their own counter starting at zero.
- Each
executecall of a Batch Apex job is a separate transaction. A static variable set in oneexecutecall is not available in the next. - Each test method runs in its own context, so a static variable changed in one test method does not carry over to the next.
- Do not use a static variable to store data you need later, such as a running total across a data load. Store it in a record or a custom setting.
The next chapter looks at lifetime in more detail.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Using an instance field inside a static method | Compile error | Pass the value as a parameter, or make the field static if it truly is shared |
| Expecting a static counter to persist between transactions | The value resets to its initial value | Store persistent data in a record or custom setting |
| Making every method static to avoid `new` | Code is hard to test and cannot use interfaces or polymorphism | Use instance methods when behavior depends on object state or may vary |
| Leaving shared state `public static` | Any class can change it unexpectedly | Make it `private static` and expose methods |
| Caching a record in a static map and then updating the record | Later reads return stale data | Refresh or remove the cache entry after the update |
Exercise
A class has public static Integer created = 0; and a constructor that does created++. Code runs new Item(); new Item(); new Item(); and then reads Item.created. What value does it read, and why? What happens to created when the transaction finishes and a new one starts?
Show answer
It reads 3. The variable is static, so all three objects increment the same single value that belongs to the class. When the transaction ends the value is discarded, and the next transaction starts with created back at 0.
Exercise
This method will not compile. Explain why, and give two ways to fix it. public class Greeter { private String name = 'World'; public static String greet() { return 'Hello, ' + name; } }
Show answer
greet is static, so it runs without an object, but name is an instance field that exists only inside an object. Fix 1: pass the value in, as in public static String greet(String name). Fix 2: if the greeting target really is shared by the whole class, declare the field private static String name = 'World';. Making greet an instance method also works when each object should have its own name.