• Lessons Home
Topics
Community
  1. Lessons
  2. Object-Oriented Apex
  3. Classes and Objects
  4. Constructors

      Constructors

      Constructors

      In the last lesson you created an object with new and then set each field on its own line. That works, but it is easy to forget a field and leave it null. A constructor lets an object set itself up the moment it is created.

      Writing a Constructor

      A constructor looks like a method with two differences: its name is exactly the class name, and it has no return type, not even void. It runs automatically every time you use new:

      public class Dog {
      	public String name;
      	public Integer age;
      
      	public Dog(String name, Integer age) {
      		this.name = name;
      		this.age = age;
      	}
      }
      
      Dog rex = new Dog('Rex', 3);
      

      The values in the parentheses after new Dog are passed to the constructor parameters, in order.

      The this Keyword

      Inside the constructor above, name means the parameter, because the parameter has the same name as the field. this.name means the field that belongs to the object being built. Writing this.name = name; copies the parameter into the field. Writing just name = name; copies the parameter into itself and leaves the field null.

      More Than One Constructor

      Just like methods, constructors can be overloaded. A class can offer several ways to build an object, and one constructor can hand off to another with this(...):

      public Dog(String name) {
      	this(name, 0);
      }
      

      Now new Dog('Pup') builds a dog whose age starts at 0. A this(...) call must be the first line of the constructor.

      The Default Constructor

      If you write no constructor at all, Apex quietly gives your class an empty one with no parameters, which is why new Dog() worked in the last lesson. As soon as you write your own constructor, that free one goes away. If you still want new Dog() to work, write a constructor with no parameters yourself.

      Why This Matters

      Constructors guarantee that every object starts in a valid state. Salesforce code leans on this constantly. A trigger handler, for example, often receives the records it works on through its constructor, so no caller can forget to pass them in.

      Apex Code Editor
      Sign in to Submit

      Welcome to Lightning Challenge!

      How It Works

      • • Write your solution in the code editor
      • • Connect your Salesforce org to test
      • • Submit to check if your solution passes
      • • Use hints if you get stuck

      Note

      Complete this lesson challenge to earn points and track your progress. The code editor allows you to implement your solution, and the tests will verify if your code meets the requirements.

      Wally Assistant

      Wally can't hear you

      Please sign in to access the AI Assistant

      Sign In