Sub topic 4
Constructors, chaining, and this
This chapter assumes you know basic Apex syntax, how to declare a class, and the difference between a field and a method. It covers how Apex builds objects with constructors, how one constructor can call another, and what this refers to.
What a constructor does
A constructor is a special method that runs when you create an object with new. It has the same name as the class and no return type. Its job is to put the new object into a valid starting state.
public class Account2 {
private String name;
public Account2(String name) {
this.name = name;
}
public String getName() {
return name;
}
}If you declare no constructor, Apex gives the class a default constructor with no parameters. Once you declare any constructor, that default disappears. If other code calls new Account2() after you add a parameterized constructor, it fails to compile unless you also write a no-argument version.
Overloading constructors
A class can have several constructors as long as their parameter lists differ. This is useful when callers sometimes know the starting value and sometimes do not.
The this keyword
Inside an instance method or constructor, this refers to the current object. You use it in two ways:
this.fieldreads or writes a field on the current object. It resolves the conflict when a parameter has the same name as a field.this(...)calls another constructor of the same class. This is called constructor chaining.
In the first example, this.name = name; assigns the parameter name to the field name. Without this., both names would mean the parameter, and the field would stay null.
Chaining constructors
When several constructors need the same setup, put the real logic in one constructor and have the others call it with this(...). The Counter class from this tutorial does this:
public class Counter {
public static Integer instancesCreated = 0;
public static final Integer MAX_VALUE = 100;
private Integer count;
public Counter() {
this(0);
}
public Counter(Integer startAt) {
this.count = startAt;
instancesCreated++;
}
public void increment() {
if (count < MAX_VALUE) {
count++;
}
}
public Integer getCount() {
return count;
}
}new Counter() calls this(0), which runs the second constructor. The counting logic lives in one place, so instancesCreated goes up exactly once per object.
Counter a = new Counter();
Counter b = new Counter(5);
System.debug(a.getCount()); // 0
System.debug(b.getCount()); // 5
System.debug(Counter.instancesCreated); // 2Rules and common errors
- A
this(...)call must be the first statement in the constructor. Anything before it is a compile error. - Chains must not loop. If constructor A calls B and B calls A, the code does not compile.
- Constructors are not inherited. A subclass declares its own constructors, and it can call the parent's with
super(...), also as the first statement. The inheritance chapter covers this. - A
finalinstance field must be assigned in a constructor or at its declaration. Chaining helps here because the one full constructor assigns every final field.
Summary of when to chain
Use chaining when two or more constructors share setup work. Skip it when the constructors are unrelated, or when a static factory method such as Counter.createStartingAt(5) makes the intent clearer than another overload.
Exercise
A class has the constructors Box() and Box(Integer size). The first should behave like Box(10). Write the body of Box() and say where it must appear relative to other statements in that constructor.
Show answer
The body is this(10);. It must be the first statement in the constructor. Putting any statement before it causes a compile error.
Exercise
You add public Invoice(Decimal total) to a class that had no constructors. Existing code calls new Invoice(). What happens, and how do you fix it?
Show answer
The code no longer compiles, because declaring any constructor removes the implicit no-argument constructor. Fix it by adding an explicit public Invoice() constructor, or by updating the callers to pass a value.