Sub topic 3
Instance variables and methods: state per object
This chapter assumes you know basic Apex syntax, collections such as List, and how to declare a class with an access modifier. Constructors, static members and interfaces get their own chapters. Here the focus is the part of a class that belongs to each object.
What "instance" means
A class is a blueprint. An object is one thing built from that blueprint with new. An instance member is a variable or method that belongs to a single object, not to the class as a whole.
- An instance variable (also called a field) stores data for one object. Every object gets its own copy.
- An instance method runs against one object and can read and change that object's fields.
You reach instance members through a variable that holds an object: cart.addItem(...), cart.owner. You cannot reach them through the class name.
A first example
public class ShoppingCart {
public String owner;
private List<String> items = new List<String>();
private Decimal total = 0;
public void addItem(String name, Decimal price) {
items.add(name);
total += price;
}
public Integer size() {
return items.size();
}
public Decimal getTotal() {
return total;
}
}owner, items and total are instance variables. addItem, size and getTotal are instance methods. Inside a method you can use a field by its plain name, because the method already runs on a specific object.
Run this in Anonymous Apex after saving the class:
ShoppingCart a = new ShoppingCart();
a.owner = 'Ana';
a.addItem('Pen', 2);
a.addItem('Book', 12);
ShoppingCart b = new ShoppingCart();
b.owner = 'Bo';
b.addItem('Mug', 8);
System.debug(a.size()); // 2
System.debug(b.size()); // 1
System.debug(a.getTotal()); // 14
System.debug(b.getTotal()); // 8The two carts never interfere. a.addItem changes only the items and total stored in the object that a refers to.
Variables hold references, not objects
An Apex variable of a class type does not contain the object. It holds a reference to it. Copying the variable copies the reference, so two variables can point to one object.
ShoppingCart a = new ShoppingCart();
ShoppingCart c = a; // c refers to the same object as a
c.addItem('Lamp', 30);
System.debug(a.size()); // 1, because a and c are the same cartThis matters when you pass an object to a method. The method receives a copy of the reference, so changes it makes to the object's fields are visible to the caller. Reassigning the parameter to a new object inside the method is not visible to the caller.
Default values and null
A field without an initializer starts as null. This is true for every type, including Integer, Decimal and Boolean. Apex does not use zero or false as a default for fields.
| Declaration | Starting value |
|---|---|
| `public Integer hits;` | `null` |
| `public Boolean active;` | `null` |
| `public String name;` | `null` |
| `public List<String> tags;` | `null` (not an empty list) |
| `public Integer hits = 0;` | `0` |
| `public List<String> tags = new List<String>();` | an empty list |
The most common instance-state bug follows from this table:
public class PageCounter {
private Integer hits; // null, no initializer
public void record() {
hits++; // System.NullPointerException
}
}Incrementing null throws at run time. Initialize fields at the declaration, or in a constructor, whenever you plan to do arithmetic or call methods on them. The same applies to collections: tags.add('x') on a null list fails.
Fields and methods working together
Good instance design keeps the data private and exposes behavior through methods. That lets a method protect rules about the state. The next class guards a status field so it can only change in valid ways.
public class Ticket {
public String title { get; set; }
public String status { get; private set; }
private Integer reopenCount = 0;
public Ticket(String title) {
this.title = title;
this.status = 'New';
}
public void close() {
status = 'Closed';
}
public void reopen() {
if (status == 'Closed') {
status = 'Open';
reopenCount++;
}
}
public Integer getReopenCount() {
return reopenCount;
}
}Ticket t = new Ticket('Login fails');
t.reopen(); // ignored, the ticket is not closed
t.close();
t.reopen();
System.debug(t.status); // Open
System.debug(t.getReopenCount()); // 1
// t.status = 'Closed'; // compile error, the setter is privateThree points about this code:
titleandstatusare properties. A property is a field-like instance member with agetandsetaccessor.{ get; set; }creates a hidden field for you. Puttingprivateon one accessor, as withstatus, lets outside code read the value but not change it.reopen()checks the current state before changing it. Because outside code cannot writestatusorreopenCountdirectly, the rule cannot be bypassed.this.title = titleusesthis, a reference to the current object. The constructor parameter has the same name as the property. Writingtitle = titlewould assign the parameter to itself and leave the propertynull.
Calling methods on this object
An instance method can call other instance methods of the same class by name, and can read static members. This keeps logic in one place:
public class Invoice {
private Decimal subtotal = 0;
private Decimal taxRate = 0.2;
public void addLine(Decimal amount) {
subtotal += amount;
}
public Decimal tax() {
return subtotal * taxRate;
}
public Decimal totalWithTax() {
return subtotal + tax(); // calls another instance method on this object
}
}A method can also return this, which lets callers chain calls on one object:
public class QueryBuilder {
private List<String> filters = new List<String>();
public QueryBuilder whereEquals(String field, String value) {
filters.add(field + ' = \'' + String.escapeSingleQuotes(value) + '\'');
return this;
}
public String build() {
return String.join(filters, ' AND ');
}
}
// Usage
String clause = new QueryBuilder()
.whereEquals('Name', 'Acme')
.whereEquals('Type', 'Customer')
.build();
System.debug(clause); // Name = 'Acme' AND Type = 'Customer'Access defaults and visibility
If you give a variable or method no access modifier, it is private to the class. Write public explicitly for anything callers need. The usual practice is private fields with public methods or properties. This lets you change how data is stored later without breaking callers.
How long instance state lives
An object exists for as long as something references it during the running transaction. When the transaction ends, all instance state is gone. A new transaction that creates new ShoppingCart() starts with empty fields, whatever the previous transaction did. If you need data to survive, save it in a record, a custom setting or another storage mechanism. Instance variables are not storage. The next chapters contrast this with static state.
Common errors
- Using an instance member without an object. Writing
ShoppingCart.size()fails to compile, because there is no particular cart to ask. - Forgetting to initialize a numeric or collection field, then hitting a
NullPointerException. - Assuming that
b = acopies the object. It copies the reference. - Naming a parameter like a field and leaving out
this.. - Making every field
public. Any code can then put the object into an invalid state.
Exercise
A class declares private Integer total; with no initializer and a method add(Integer n) containing total += n;. What happens on the first call to add(5) on a new object, and what are two ways to fix it?
Show answer
The call throws a System.NullPointerException, because total starts as null and Apex does not default Integer fields to 0. Fix it by initializing the field at its declaration (private Integer total = 0;) or by assigning 0 in a constructor.
Exercise
Given ShoppingCart a = new ShoppingCart(); ShoppingCart b = a; b.addItem('Pen', 2);, how many items does a.size() return, and why?
Show answer
It returns 1. The assignment b = a copies the reference, not the object, so a and b refer to the same cart and the item added through b is visible through a.