Sub topic 4
Constructors, chaining, and this
A constructor is the code that runs when you create an object with new. This chapter covers how to declare constructors, how to overload them, how one constructor can call another with this(...), and how the this keyword refers to the current object. It assumes you can read basic Apex and know what a class, a field, and a method are. Earlier chapters covered declaring classes, access modifiers, and instance members.
What a constructor is
A constructor has the same name as its class and no return type. It runs once per object, after memory for the object is set up and before new hands the object back to you. Its job is to put the new object into a valid starting state.
public class Greeter {
private String name;
public Greeter(String name) {
this.name = name;
}
public String greet() {
return 'Hello, ' + name;
}
}Greeter g = new Greeter('Ana');
System.debug(g.greet()); // Hello, AnaIf you write no constructor, Apex supplies a default one that takes no arguments. The default disappears as soon as you declare any constructor yourself. This is the most common constructor error in Apex:
public class Tag {
public String label;
public Tag(String label) {
this.label = label;
}
}
// Tag t = new Tag(); // Compile error: no no-argument constructor existsIf you still want new Tag() to work after adding a parameterized constructor, declare the no-argument constructor explicitly.
Always write the access modifier on a constructor so the intent is visible. A public constructor lets other classes create objects. A private constructor limits creation to code inside the class, which is the basis of the factory and singleton patterns shown later.
Overloading constructors
A class can have several constructors as long as their parameter lists differ in number or type. This is called overloading. Apex picks the constructor that matches the arguments at the call site.
| Call | Constructor chosen |
|---|---|
| `new Notification('[email protected]')` | One `String` parameter |
| `new Notification('[email protected]', 'Welcome')` | Two `String` parameters |
| `new Notification('[email protected]', 'Welcome', 1)` | `String`, `String`, `Integer` |
Two constructors cannot share the same parameter types, even if the parameter names differ. Passing a bare null can also be ambiguous when two overloads accept different reference types, so cast it or pass a typed variable.
Chaining with this(...)
Overloaded constructors tend to repeat the same assignments. Constructor chaining removes the repetition. A constructor can call another constructor of the same class with this(...). The shorter constructors supply default values and delegate to the fullest one, so the real setup and validation live in one place.
public class Notification {
private final String recipient;
private final String subject;
private final Integer priority;
public Notification(String recipient) {
this(recipient, 'No subject');
}
public Notification(String recipient, String subject) {
this(recipient, subject, 3);
}
public Notification(String recipient, String subject, Integer priority) {
if (String.isBlank(recipient)) {
throw new IllegalArgumentException('recipient is required');
}
this.recipient = recipient;
this.subject = subject;
this.priority = priority;
}
public String summary() {
return String.valueOf(priority) + ' | ' + recipient + ' | ' + subject;
}
}Notification n1 = new Notification('[email protected]');
Notification n2 = new Notification('[email protected]', 'Welcome', 1);
System.debug(n1.summary()); // 3 | [email protected] | No subject
System.debug(n2.summary()); // 1 | [email protected] | WelcomeThe validation runs for every construction path because all three constructors end up in the last one. The final fields (covered in a later chapter) can be assigned once, in the constructor that does the real work.
Order of execution
When you call new Notification('[email protected]'), the constructors are entered from the shortest to the fullest. Each this(...) call finishes before the remaining statements of the calling constructor run. So the bodies complete in the opposite order, fullest first.
Rules for this(...)
this(...)must be the first statement in the constructor. Putting any statement before it is a compile error.- Only one
this(...)orsuper(...)call is allowed per constructor, and it cannot be used from a method. - Chains must not loop. If constructor A calls B and B calls A, the code never finishes constructing.
The this keyword
Inside an instance method or constructor, this is a reference to the object currently being worked on. It has three common uses.
- Separating a field from a parameter with the same name. This is the most frequent use.
- Calling another constructor with
this(...), as above. - Passing the current object to another method.
Parameter shadowing
When a parameter has the same name as a field, the parameter hides the field inside that constructor. This is called shadowing. Without this., an assignment changes only the parameter and the field is never set.
public class Account2 {
private String name;
public Account2(String name) {
name = name; // Bug: assigns the parameter to itself, field stays null
}
public Account2(String name, Boolean fixed) {
this.name = name; // Correct: field on the left, parameter on the right
}
public String getName() {
return name;
}
}A different fix is to name parameters differently, for example initialName. Either approach works. Pick one convention for the codebase.
Passing this to another method
public class Registry {
private static List<Widget> all = new List<Widget>();
public static void add(Widget w) {
all.add(w);
}
public static Integer size() {
return all.size();
}
}
public class Widget {
public Widget() {
Registry.add(this);
}
}Be careful with this pattern. The constructor has not finished when it hands out this, so another piece of code could see a half-built object. Register the object only after all fields are set, or have the caller do it.
Static context has no this
Static methods and static initialization blocks belong to the class, not to an object. There is no current object, so this is a compile error there. The next chapters cover the static side in detail.
Private constructors and factory methods
Making a constructor private forces callers to go through a method you control. A static factory method has a name, which a constructor does not, and it can return a cached object instead of a new one. The Counter.createStartingAt method in the topic's first example is a small instance of this idea.
A singleton uses the same technique to guarantee one object per transaction:
public class AppSettings {
private static AppSettings instance;
public final Integer pageSize;
private AppSettings() {
this.pageSize = 50;
}
public static AppSettings getInstance() {
if (instance == null) {
instance = new AppSettings();
}
return instance;
}
}AppSettings a = AppSettings.getInstance();
AppSettings b = AppSettings.getInstance();
System.debug(a === b); // trueThe static variable instance lives only for the current transaction, so each new transaction builds its own copy. === compares references, which confirms both variables point to the same object.
Field initializers and construction order
Fields can have initial values written beside their declaration:
public class Basket {
private List<String> items = new List<String>();
private Integer capacity = 10;
public Basket() {
// items and capacity are already set here
}
}Initializers run before the constructor body, so the body can rely on them. This is why you rarely need to write items = new List<String>() inside a constructor. If a field has an initializer and the constructor also assigns it, the constructor's value wins because it runs later.
Constructors in subclasses
A subclass constructor must also build the parent part of the object. It does this with super(...), which follows the same first-statement rule as this(...). If you write neither, Apex calls the parent's no-argument constructor for you. If the parent has no such constructor, you get a compile error and must call super(...) with arguments. The inheritance chapter shows this with virtual and abstract classes.
Common mistakes
- Adding a parameterized constructor and then calling
new ClassName()with no arguments. - Writing
name = name;and wondering why the field isnull. - Placing a statement before
this(...). - Duplicating validation in every overload instead of chaining to one constructor.
- Passing
thisout of a constructor before the object is fully initialized. - Doing heavy work in a constructor, such as queries or DML. Constructors run on every
new, so keep them to assigning state and validating input.
Exercise
A class declares only public Tag(String label). A teammate writes Tag t = new Tag(); and gets a compile error. Give two ways to fix it and say which one is better if an empty label should never be allowed.
Show answer
Either add an explicit no-argument constructor to Tag, or change the call to pass a label, as in new Tag('news'). If an empty label must never be allowed, change the call site and keep only the parameterized constructor. Adding a no-argument constructor would let callers create a Tag with no label. If you do need a no-argument form, make it chain with this('default') so validation still runs in one place.
Exercise
What does this code print, and why? In the constructor public Box(Integer size) { size = size; } the class has a field private Integer size; and a method getSize() that returns the field. The code is System.debug(new Box(5).getSize());
Show answer
It prints null. Inside the constructor, the parameter size shadows the field size, so size = size assigns the parameter to itself and the field is never set. The fix is this.size = size;.