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

Every class you write gets a free, invisible "default constructor" — a no-parameter new ClassName() that creates an empty object with every field left at its default (usually null). 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);

A constructor is a method with the same name as the class and no return type. this.eventName refers to the object being built; eventName (without this.) refers to the incoming parameter — this is what tells them apart when the names match.

Once you write one constructor, the default disappears

EventTicket broken = new EventTicket(); // compile error!

As soon as a class defines its own constructor, Apex stops providing the free no-argument one automatically. 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; }

APEX

Constructors Quiz

1. What happens to the default no-argument constructor once you write your own custom constructor?

Log in to submit the quiz and save your score.

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.