Beginner
20 min read
Constructors
By the end of this lesson, you'll be able to:
- Explain what a constructor is and when it runs
- Write a custom constructor that accepts parameters
- Distinguish the default constructor from a custom one
Prerequisites: "Creating Your First Class"
The default constructor
public class EventTicket {
public String eventName;
public Decimal price;
}
EventTicket ticket = new EventTicket(); // uses the invisible default constructor
public class EventTicket {— the blueprint, with no constructor written.public String eventName;— a field.public Decimal price;— another field.}— closes the class.- (blank line)
EventTicket ticket = new EventTicket();— every class you write gets a free, invisible "default constructor" — a no-parameternew ClassName()that creates an empty object with every field left at its default (usuallynull). This is what every lesson so far has actually been using.
Writing a custom constructor
public class EventTicket {
public String eventName;
public Decimal price;
public EventTicket(String eventName, Decimal price) {
this.eventName = eventName;
this.price = price;
}
}
EventTicket ticket = new EventTicket('Tech Conference', 1200);
public class EventTicket {— the blueprint.public String eventName;— a field.public Decimal price;— another field.- (blank line)
public EventTicket(String eventName, Decimal price) {— a constructor: a method with the same name as the class and no return type.this.eventName = eventName;—this.eventNamerefers to the object being built;eventName(withoutthis.) refers to the incoming parameter —thisis what tells them apart when the names match.this.price = price;— same pattern for the price.}— closes the constructor.}— closes the class.- (blank line)
EventTicket ticket = new EventTicket('Tech Conference', 1200);— nownewtakes arguments, which flow straight into the constructor's parameters.
Once you write one constructor, the default disappears
EventTicket broken = new EventTicket(); // compile error!
EventTicket broken = new EventTicket();— as soon as a class defines its own constructor (asEventTicketnow does), Apex stops providing the free no-argument one automatically — this line no longer compiles. If you still want a no-argument option, you have to write it explicitly, alongside your custom one.
Exercise
Add a constructor to the Book class from the previous lesson that accepts title and pageCount as parameters and sets them using this.
Show hint
public Book(String title, Integer pageCount) { this.title = title; this.pageCount = pageCount; }
Constructors Quiz
Leaderboard
- 1. Monde Masiza 1/1
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A constructor is special code that runs automatically when an object is created with new — it's the natural place to set up an object's initial data.