Chapter 5 - Java for Beginners Course

Class Declaration - Constructors

In the first part of the class declaration we did a recap of what was covered in Chapter 1 and added some more examples and a more formal view of the declarations for classes, methods and fields.

In this part we’ll cover an important concept we haven’t yet introduced: Constructors.

What are Constructors?

You can think of constructors as methods that are responsible of initializing the objects of a class during their creation process. They are used to set the initial state of the object, in some cases to default values, or in some cases to values driven by the input parameters.

Constructor declaration

Constructors have a very similar declaration syntax to methods:

[constructor modifiers] ClassName([ConstructorParameters]) [throws Exceptions] {
	// constructor body
}

The main differences are that:

  • They don’t specify a return type and,

  • The "methodName" is the same as the name of the class that defines them.

For example:

public Light() {
    //...
}

is a valid constructor for our Light class.

We’ll cover the throws keyword in a future course.

How do we invoke constructors?

We mentioned that constructors are very similar to methods, however, we can’t invoke them as we do with regular methods using the dot (.) operator.

Constructors are the methods called when we use the new operator when we create new objects.

Let’s use our Light class to show some examples:

Example 1 - Constructor with no parameters

public class Light {
    private boolean on;

    private String color;

    private int power = 0;

    public Light() {
        on = false;
        color = "WHITE";
    }

    // ...
}

In this case, our constructor doesn’t require any inputs and we’re defining default values for the fields in our object (light is turned off by default and we say the light has a "WHITE" color for when it is turned on).

We can then use this constructor when we create a new Light object, for example:

Light bedroomLight = new Light();
bedroomLight.printLightDetails();

Output:

The light is turned off with color: WHITE and power set to: 0%

In this example, when we invoke new Light(); it will execute our constructor with no parameters defined above.

Example 2 - Constructor with parameters

As our Light class defines some state, we might want to allow users of the Light class to initialize it with some specific values. We could do the following in this case:

public Light(boolean isLightOn, String lightInitialColor) {
    on = isLightOn;
    color = lightInitialColor;
}

This is another valid constructor, the main difference being that when we create the object we can define what initial values we want. This constructor in particular allows us to set whether we want the light on/off and the initial color we want to set.

To use this constructor, we just pass in the parameters when we use the new keyword, as follows:

Light studioLight = new Light(true, "YELLOW");
studioLight.printLightDetails();

Output:

The light is turned on with color: YELLOW and power set to: 0%

In this example, when we invoke new Light(true, "YELLOW"); the constructor with parameters we defined above will be used to construct & initialize the Light object.

Additional notes on constructors:

Constructor overloading

Similar to methods, Constructors can be overloaded. This means, you can define more than one constructor in a class as long as they have a different parameter list.

In our case, both Constructors can be added to the Light class as they have different parameters.

Default constructor

If you recall in Chapter 1, when we introduced the new keyword, we were using the Airplane class which didn’t define any constructors and we could still do this:

Airplane plane1 = new Airplane();

The reason this works is that, by default, if no constructor is explicitly defined in the class, the Java compiler will add a constructor with the following characteristics:

  • It is public

  • It doesn’t have any parameters

  • It invokes a parameter-less constructor in its superclass (We’ll cover this in detail in the Inheritance section)

So, in our Airplane case, even though we didn’t add a constructor ourselves, the Java compiler will add one for us.

Calling other constructors in the same class

We can invoke one constructor from another one. This would allow us to avoid repeating our code in multiple constructors if they do very similar things.

To do this, you use the this keyword as you’d do with a method invocation (for example, this() to invoke a constructor with no parameters). Java will invoke the constructor that matches the parameter types you use.

There are rules around this, however, at this stage keep in mind that you can only do this as the first line in a constructor. We’ll cover more rules about constructors invoking other constructors later in this chapter.

For example, in our Light class, we can convert our 2 constructors we have above, from this:

public Light() {
    on = false;
    color = "WHITE";
}

public Light(boolean isLightOn, String lightInitialColor) {
    on = isLightOn;
    color = lightInitialColor;
}

Into this:

public Light() {
    this(false, "WHITE");
}

public Light(boolean isLightOn, String lightInitialColor) {
    on = isLightOn;
    color = lightInitialColor;
}

You can see that our constructor with no parameters is using the this(…​) keyword which tells Java we want to invoke the constructor in this same class with (false,"WHITE") as the parameters.