Sub topic 7
Static versus instance: what can access what
This chapter assumes you can declare an Apex class with fields, methods, and constructors, and that you know the difference between an instance member and a static member. It also assumes you know that Apex code runs inside a transaction. Here you will learn which kind of member can reach which, why the compiler enforces those rules, and what they mean for design.
The core rule
Every member has an owner. An instance member belongs to one object, and each new creates a fresh copy. A static member belongs to the class, and only one copy exists in the running transaction.
Access follows from ownership:
- Instance code runs on a specific object, so it can see that object's fields and the class's static members.
- Static code runs with no object, so it can see only static members. It has no
this.
The reasoning is simple. A static method can be called when zero objects exist, or when a thousand exist. If it could read net, the compiler could not say which object's net you mean.
| Code location | Instance fields and methods | Static fields and methods | `this` |
|---|---|---|---|
| Instance method or constructor | Yes | Yes | Yes |
| Static method | Only through an object reference | Yes | No |
| Static initialization block | Only through an object reference | Yes | No |
| Instance initialization block | Yes | Yes | Yes |
A worked example
The Invoice class below uses both kinds of members. The static nextNumber hands out invoice numbers, so every object takes its number from one shared counter. The instance field number stores that object's own number.
public class Invoice {
// Static: one copy for the class
private static Integer nextNumber = 1000;
private static final Decimal TAX_RATE = 0.2;
// Instance: one copy per object
private final Integer number;
private Decimal net;
public Invoice(Decimal net) {
this.number = nextNumber++; // instance code can read and write static state
this.net = net;
}
public Integer getNumber() {
return number;
}
public Decimal gross() {
return net * (1 + TAX_RATE); // instance method reads a static constant
}
public static Decimal grossFor(Decimal netAmount) {
return netAmount * (1 + TAX_RATE); // static method reads a static constant
// return net; // does not compile: net belongs to an object
// return this.net; // does not compile: there is no "this" here
}
public static Invoice merge(Invoice first, Invoice second) {
// Allowed: the objects are passed in, so their private members are reachable
return new Invoice(first.net + second.net);
}
}
// Usage
Invoice a = new Invoice(100);
Invoice b = new Invoice(50);
System.debug(a.getNumber()); // 1000
System.debug(b.getNumber()); // 1001
System.debug(Invoice.grossFor(10)); // 12.0
System.debug(Invoice.merge(a, b).gross()); // 180.0Three details in this example matter.
- The constructor increments
nextNumber. Constructors are instance code, so they can change static state. This is how theinstancesCreatedcounter in the earlierCounterexample works. mergeis static, yet it readsfirst.net. The restriction is about the missing implicit object, not about the data being private or hidden. Once you hold a reference, access is governed by the usual modifiers. Becausemergeis insideInvoice, it can useprivatemembers of anyInvoice.- The commented lines in
grossForshow the typical compile error. When you see one, the fix is usually to pass the data in as a parameter, or to make the method an instance method.
Calling a static member from outside
From other classes, reach static members through the class name: Invoice.grossFor(10). Apex does not let you reach a static member through an instance variable. Writing a.grossFor(10) is a compile error, unlike in Java, where it is allowed but discouraged. This is a useful guard, because the class name tells the reader that no object is involved.
Inside the class, you can use a bare name such as TAX_RATE or nextNumber from either kind of code. If an instance field and a static field share a name, this.name picks the instance one. Avoid the clash, though, because it hurts readability.
Static state is shared, but only within one transaction
Static variables are initialized the first time the class is used in a transaction. They stay alive until that transaction ends. They do not persist between transactions, and they are not shared between users or between concurrent transactions. Each transaction gets its own fresh copy.
This makes statics a good fit for transaction-wide bookkeeping, such as the recursion guard from the chapter on static lifetime. It makes them a poor fit for storing anything that must survive the request, such as a user's preferences or a running total across days. Use a custom setting, a custom object, or a platform cache for those.
Two further points follow from this.
- Statics are shared by all code in the transaction. A trigger, a flow-invoked action, and a helper class that all touch
Invoice.nextNumbersee the same value. This is useful for coordination and hazardous for hidden coupling. - Static initializers run in the order they appear in the class, at first use. A static field that depends on another static field must be declared after it.
A common gotcha: the Boolean guard
The TriggerGuard example uses a single Boolean. It works for one record. It breaks in bulk operations. When a transaction touches more than 200 records, Salesforce calls the trigger once per chunk of 200 records, and every chunk runs in the same transaction. A Boolean set during the first chunk makes the second chunk skip its work.
A safer guard tracks record IDs:
public class AccountTriggerHandler {
private static Set<Id> processedIds = new Set<Id>();
public static List<Account> filterUnprocessed(List<Account> accounts) {
List<Account> toProcess = new List<Account>();
for (Account acc : accounts) {
// Set.add returns true only if the value was not already in the set
if (acc.Id != null && processedIds.add(acc.Id)) {
toProcess.add(acc);
}
}
return toProcess;
}
}Each record is processed once per transaction, and new chunks still get their work done. Note that a record that is legitimately updated a second time in the same transaction (for example by a workflow field update) will also be skipped. If you need that second pass, key the guard on something more specific, such as the ID plus the changed field values.
Trade-offs of static design
Static methods are cheap to call and need no object, which suits stateless helpers such as Invoice.grossFor. The costs show up elsewhere.
- Testing. A static method cannot be replaced with a stand-in. If
OrderServicecallsPricingUtil.lookup()directly, a unit test cannot substitute a fakePricingUtil. An instance method on an interface type can be swapped. The design chapter returns to this. - Hidden state. Static variables act as global variables for the transaction. Two unrelated features that both read and write the same static can interfere with each other, and the bug appears only when both run in one transaction.
- No polymorphism. Static methods cannot be virtual, abstract, or overridden. If behavior must vary by type, you need instance methods.
- Ordering dependence. Code that relies on a static having been set earlier will behave differently when a test runs it in isolation.
A practical rule: use static for constants, stateless helpers, factory methods, and transaction-scoped guards. Use instance members for anything with identity or behavior that might vary.
Inner classes
Apex allows static members only in top-level classes, not in inner classes. An inner class can still read the static members of its outer class. The chapter on inner classes covers the details.
Exercise
A trigger handler uses private static Boolean hasRun = false; as a guard and sets it to true after the first call. A data load inserts 450 Accounts in one transaction. What happens to records 201 through 450, and what change fixes it?
Show answer
The trigger fires once per chunk of 200 records, and all chunks run in the same transaction. Static state lives for the whole transaction, so hasRun is already true when chunks two and three arrive, and those records are skipped. Replace the Boolean with a static Set<Id> of processed record IDs and use the result of processedIds.add(id) to decide whether a record needs processing.
Exercise
Which lines in this class fail to compile, and why? public class Box { private Integer size = 3; private static Integer total = 0; public static Integer peek(Box b) { return b.size; } // line 1 public static Integer bad() { return size; } // line 2 public Integer ok() { return total + size; } // line 3 }
Show answer
Only line 2 fails. A static method has no current object, so the bare name size has no owner. Line 1 compiles because the object b is passed in, and Box code may read the private fields of any Box. Line 3 compiles because instance methods can read both instance and static fields.