Sub topic 3
Instance variables and methods: state per object
This chapter assumes you can read basic Apex syntax, use List and Map, and know that Apex code runs inside Salesforce transactions. It also assumes you know what a class declaration looks like. The chapter covers instance members, the fields and methods that belong to each object you create.
What "instance" means
A class is a template. An instance is one object built from that template with the new keyword. Each instance gets its own copy of every instance variable, so changing one object's data does not touch another's.
An instance variable is declared in the class body without the static keyword. An instance method is a method declared the same way, and it can read and change that object's variables.
public class Account Tracker {
}The block above is not valid, because a class name cannot contain a space. Here is a correct, complete example.
public class Counter {
private Integer count;
public Counter(Integer startAt) {
this.count = startAt;
}
public void increment() {
count++;
}
public Integer getCount() {
return count;
}
}
// Usage
Counter a = new Counter(0);
Counter b = new Counter(10);
a.increment();
a.increment();
b.increment();
System.debug(a.getCount()); // 2
System.debug(b.getCount()); // 11Objects a and b came from the same class, but each one holds its own count. Calling increment() on a changes only a.
How instance members are reached
You reach an instance member through a reference to an object, using dot notation: a.increment(). Inside the class, you can name the variable directly (count) or write this.count. The this keyword means "the current object". It is useful when a parameter has the same name as a field, as in this.count = count.
Default values and null references
An instance variable you do not assign starts as null. This is true for Integer, String, Boolean, and other types. Apex does not give numeric fields a default of zero. Using such a field in arithmetic throws a NullPointerException.
public class Order {
public Integer quantity; // null until assigned
public Integer quantityOrZero = 0; // safe starting value
}The same applies to the object reference itself. If you declare Counter c; without new, then c is null, and c.increment() throws a NullPointerException.
Keep state private, expose behavior
A common pattern is to mark variables private and offer public methods to read or change them. This lets the class protect its own rules. In Counter, outside code cannot set count to a negative number, because the only way to change it is increment().
Apex also has property syntax, which gives you a getter and setter in one line.
public class Person {
public String name { get; set; }
public Integer age { get; private set; }
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public void haveBirthday() {
age++;
}
}Here name can be read and written from anywhere, while age can be read anywhere but changed only inside the class.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Calling an instance method on a `null` reference | `NullPointerException` | Create the object with `new` first |
| Using an unassigned `Integer` field in math | `NullPointerException` | Give the field an initial value |
| Expecting two objects to share a field | Each object has a separate copy | Use a static variable if sharing is intended |
| Assigning one object variable to another and expecting a copy | Both variables refer to the same object | Create a new object instead |
Exercise
A class has the field private Integer total; with no initial value and the method public void add(Integer n) { total += n; }. You create an object with new and call add(5). What happens, and how do you fix it?
Show answer
It throws a NullPointerException, because total is null and null cannot be used in arithmetic. Fix it by declaring the field as private Integer total = 0; or by assigning 0 in a constructor.