Java calling one constructor from another

Very often we write multiple constructors to make a possibility to create objects with different initial state. Those constructors very often in large part do the same thing. Instead of rewriting the same code in every constructor, we can call one constructor from another. In this article I explain how to do this.

Example

Take a loot at the example code below:

public class Prototyping {
   public static void main(String[] args) {
      BMWCar car = new BMWCar("520d");
      System.out.println("Car model: "+car.model);
      System.out.println("Car fuel type: "+car.fuelType);
      System.out.println("Car color: "+car.color);
   }
}

class BMWCar {
   public String model, fuelType, color = "black";

   public BMWCar(String model) {
      this.model = model;
      this.fuelType = model.contains("d") ? "diesel" : "petrol";
   }

   public BMWCar(String model, String color) {
      this(model); // Calling BMWCar(String) constructor
      this.color = color;
   }
}

Our BMWCar class has three fields: model, fuelType and color. The class has also two constructors:

BMWCar(String) takes car model as an argument. This constructor sets car’s model and determines its fuelType.

BMWCar(String,String) takes car model and color as an argument. This constructor sets the car’s color, but also sets car’s model and determines its fuelType.

Instead of rewriting the code from the first constructor to the second constructor, we simply execute the first constructor from the second constructor. That way we make the code cleaner, easier to read and more manageable.

Explanation

To call one constructor from another we use this() construct. Note, that in that case this isn’t a reference to object, but a special Java construct built specially to call constructors from other constructors. Simply use this() and pass parameters from the desired constructor to call it.

One important note: this() must be always called as the first statement in the constructor. It means that if you want to use this() in your constructor, it must be placed as the very first line inside the constructor where you want to use this(). If you will not that, Java compiler will throw an error during compilation time.

Learn more about Java