3.6 Use constructor to initialise

The concept

Thinking of our Dog class, we might have a feeling that name is a Mandatory attribute that every dog should have one. And it shouldn’t be easily changed afterwards.

In order to do this, we have the following code. Let’s reopen our Dog class.

public class Dog
    public Integer age;
    private String name;
    private String gender;
    public String breed;
    public Boolean isPuppy;
    public Dog(String name) 
        this.name = name;
    public void greeting()
        System.debug('Hello, my name is ' + name);

And in our anonymous block:

Dog d = new Dog('Happy');

Execute it and see the result by yourself.

A bit explanation

The constructor is the initialiser of a class. It almost has the same grammar as a normal function. The differences are: it has to use the class name as function name and has no return type, not even void. And it cannot return any value.

If there is no constructor defined. Apex will have a default constructor for that class, which basically does nothing. That’s why we could use Dog d = new Dog() in our previous cases, but not now. If you still use Dog d = new Dog(), you will get a compiler error.

Constructors can be overloaded, just like other functions. Function overloading will be further explained in Chapter 3.8.

Constructor takes the parameters inside the new Dog(…) parenthesis.

Constructor can only be called once for each object, which is during initialisation time.

What is ‘this’

You might have already realized that we have used a keyword this in our code sample. This keyword is used inside the class definition body, which means current object. Although the actual object instance it not there yet, we can understand it as whatever your object instance is, I – this – represent your current object.

So in our code sample, in the line:

this.name = name;

There are two name variables defined – one is from the constructor’s parameter list, the other is in the class. By default, name means the function’s variable here. This is called variable shadowing. So, if we want to explicitly refer to the object’s name, we need to use the keyword this.


For our previous Commodity class, define a constructor for that which takes the price as the constructor.

Next Post

3.7 Using static modifier

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

Your email address will not be published / Required fields are marked *