Sub topic 8
Constants with final and static final
This chapter assumes you can read basic Apex, know how instance and static members differ, and understand that static state lives for one transaction. It covers how final works on its own, how static final creates a true constant, and the mistakes that trip people up.
What final means
The final keyword says a variable can be assigned only once. After that, any attempt to change it is an error. You can assign the value at the declaration, in a constructor, or in an initialization block.
A final variable that is not static is an instance variable. Each object gets its own copy, and each copy can hold a different value. The value is fixed only once the object has been built.
public class Order {
public final String orderNumber;
public final Datetime createdAt = Datetime.now();
public Order(String orderNumber) {
this.orderNumber = orderNumber;
}
}
// Usage
Order o = new Order('A-100');
System.debug(o.orderNumber); // A-100
// o.orderNumber = 'B-200'; // compile error: final variablestatic final: a class-level constant
Adding static gives you one copy that belongs to the class. Together, static final is how Apex defines a constant. By convention, constant names use upper case with underscores.
public class Limits2 {
public static final Integer MAX_RETRIES = 3;
public static final String DEFAULT_STATUS = 'New';
}
// Usage
System.debug(Limits2.MAX_RETRIES); // 3You reach the constant through the class name, so no object is needed. Constants keep "magic values" in one place. If the retry count changes, you edit one line instead of searching every file.
Assigning a constant in a static block
A simple constant fits in one expression. Collections often need more setup. A static initialization block runs once, when the class is first used, and it may assign a static final variable that was declared without a value.
public class Config {
public static final Map<String, Integer> LIMITS;
static {
LIMITS = new Map<String, Integer>{
'small' => 10,
'large' => 1000
};
}
}
// Usage
System.debug(Config.LIMITS.get('small')); // 10Because the class loads once per transaction, the block runs once per transaction. The next transaction starts fresh and runs it again.
Final means the reference, not the contents
This is the most common surprise. final stops you from reassigning the variable. It does not stop you from changing the object the variable points to. A final list or map can still have items added or removed.
public class Registry {
public static final List<String> NAMES = new List<String>{ 'a' };
}
// Usage
Registry.NAMES.add('b'); // allowed, the list changes
System.debug(Registry.NAMES.size()); // 2
// Registry.NAMES = new List<String>(); // compile errorIf you need a collection that nobody can change, expose it through a method that returns a copy, or keep it private and offer read-only access.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Assigning a final variable twice | Compile error | Assign once, or drop `final` |
| Expecting a final list to be unmodifiable | Items can still be added | Return a copy from a method |
| Using `final` where each object needs its own value | Value is fixed after construction | Assign in the constructor |
| Declaring `final` without any assignment | Compile error | Assign it at the declaration, in a constructor, or in a block |
Exercise
A class declares public static final List<String> TAGS = new List<String>();. Another class runs MyClass.TAGS.add('x');. Does this compile, and why?
Show answer
Yes, it compiles. final prevents reassigning TAGS to a different list, but it does not make the list itself unmodifiable, so add works. Only a statement like MyClass.TAGS = new List<String>(); would be an error.
Exercise
You need a constant map that takes several lines to build. Where do you assign it, and when does that code run?
Show answer
Declare it as public static final Map<...> with no value, then assign it inside a static { } block. The block runs once, when the class is first used in a transaction.