Learn Java

Java Constructor

Constructors are special methods that initialize a new object of the class. A constructor of a class is invoked when an instance is created using the new keyword.

A constructor is different from other methods in that:

  • it has the same name as the class that contains it;
  • it has no return type (not even void).

Constructors initialize instances (objects) of the class. They set values to the fields when the object is created. Also, constructors can take parameters for initializing fields by the given values.

Using constructors

Here is a class named Patient. An object of the class has a name, an age, and a height. The class has a constructor with 3 parameters to initialize objects with specific values.

class Patient {

    String name;
    int age;
    float height;

    public Patient(String name, int age, float height) {
        this.name = name;
        this.age = age;
        this.height = height;
    }
}

Let's go further and create some instances of the class using the constructor we've written:

Patient patient1 = new Patient("Heinrich", 40, 182.0f);
Patient patient2 = new Patient("Mary", 33, 171.5f);

Now we have two patients, Heinrich and Mary, with the same fields, but the values of those fields are different.

Keyword this

In the example above, the Patient constructor takes three parameters:

this.name = name;
this.age = age;
this.height = height;

To initialize the fields, the keyword this is used, which is a reference to the current object. Usually, this is used when an instance variable and a constructor or a method variable share the same name. It helps to disambiguate these situations.

If you write something like name = name, it means that you're assigning the name variable to itself, which, of course, doesn't make any sense. Frankly speaking, you may distinguish two objects simply by assigning another name to the variable, like name = newName. It is not prohibited, but it is considered bad practice since these variables point to the same thing. These are the reasons why the keyword this is extremely useful with constructors, fields, and methods. The absence of extra variables makes the code look clearer and less overloaded.

Default and no-argument constructor

The compiler automatically provides a default no-argument constructor for any class without constructors. Check out this block of code:

class Patient {

    String name;
    int age;
    float height;
}

We can create an instance of the class Patient using the no-argument default constructor:

Patient patient = new Patient();

In this case, all fields will be filled with the default values of their types.

If you define a specific constructor, the default constructor will not be created.

We can also define a constructor without any arguments, but use it to set default values for fields of a class. For example, we can initialize name with "Unknown":

class Patient {

    String name;
    int age;
    float height;

    public Patient() {
        this.name = "Unknown";
    }
}

Such no-argument constructors are useful in cases when any default value is better than null.

To sum up

  • Any Java class has a constructor to initialize objects;
  • A constructor has the same name as the class containing it;
  • A constructor has no return type, not even void;
  • If a class has no explicit constructors, the Java compiler automatically provides a default no-argument constructor;
  • If we want to introduce new variables to denote the same thing, make the code clearer and less loaded with extra unnecessary variables, the keyword this is used.

Multiple constructors

Sometimes we need to initialize all fields of an object when creating it, but there are cases in which it might be appropriate to initialize only one or several fields. Fortunately, for this purpose, a class can have several constructors that assign values to the fields in different ways. In this topic, you will learn how to work with multiple constructors and define the way they interact with each other.

Constructor overloading

Another feature of constructors is called constructor overloading where you can define as many constructors as you need. Each constructor should have a name that matches the class name but the parameters should be different.

In Java, constructor overloading is the practice of creating multiple constructors for a class, each with a unique parameter list.

Here is an example to understand this concept:

public class Robot {
    String name;
    String model;

    public Robot() {
        this.name = "Anonymous";
        this.model = "Unknown";
    }

    public Robot(String name, String model) {
        this.name = name;
        this.model = model;
    }
}

The Robot class has two constructors:

  • Robot() is a no-argument constructor that initializes fields with default values;
  • Robot(String name, String model) takes two parameters and assigns them to the corresponding fields.

To create an instance of the Robot class, we can use either of the two constructors:

Robot anonymous = new Robot(); // name is "Anonymous", model is "Unknown"
Robot andrew = new Robot("Andrew", "NDR-114"); // name is "Andrew", model is "NDR-114"

Bear in mind that you cannot define two constructors with the same number, types, and order of parameters!

Invoking constructors from other constructors

We can also invoke a constructor from another one. It allows you to initialize one part of an object by one constructor and another part by another constructor.

Calling a constructor inside another one is done using this. For example:

this(); // calls a no-argument constructor

If you call a constructor that has parameters, you can pass some arguments:

this("arg1", "arg2"); // calls a constructor with two string arguments

Remember, the statement for invoking a constructor should be the first statement in the body of a caller constructor.

Here is an extended example of the Robot class:

public class Robot {
    String name;
    String model;
    int lifetime;

    public Robot() {
        this.name = "Anonymous";
        this.model = "Unknown";
    }

    public Robot(String name, String model) {
        this(name, model, 20);
    }

    public Robot(String name, String model, int lifetime) {
        this.name = name;
        this.model = model;
        this.lifetime = lifetime;
    }
}

Now, the class has three constructors:

  • Robot() is a no-argument constructor;
  • Robot(String name, String model) is a two-argument constructor that invokes another constructor;
  • Robot(String name, String model, int lifetime) is a three-argument constructor that fills all fields.

The second constructor invokes the third one and passes namemodel, and lifetime = 20 to it. The third constructor, in its turn, initializes all fields of the created object.

Let's add an output to the third constructor and see the result:

public Robot(String name, String model, int lifetime) {
    this.name = name;
    this.model = model;
    this.lifetime = lifetime;
    System.out.println("The third constructor is invoked");
}

Let's now create an instance using the two-argument constructor.

Robot andrew = new Robot("Andrew", "NDR-114");

The program outputs:

The third constructor is invoked

Conclusion

In Java, a constructor is a special type of method used to initialize class objects when it is created using the new keyword. Constructors have the same name as the class they belong to and have no return type (not even void). They are necessary for initializing class objects and can take parameters to initialize fields with specific values. The this keyword is used in the constructor to reference the current object. If a class doesn't have explicit constructors, the Java compiler automatically provides a default no-argument constructor.

We've covered constructor overloading by creating multiple class constructors. Constructor overloading allows us to create an object of the class in different ways depending on the circumstances.

We can also invoke some constructors inside other types of constructors. All in all, Java provides many useful features for writing constructors and defining interactions between them.

Create a free account to access the full topic

“It has all the necessary theory, lots of practice, and projects of different levels. I haven't skipped any of the 3000+ coding exercises.”
Andrei Maftei
Hyperskill Graduate