Constructor in Java

A constructor in Java is a special type of method used to initialize an object. It is called at the time the object is created. It constructs values, i.e. it provides data for an object.

Constructor Creation Rules

There are two defined rules for constructors:

  1. The name must be the same as the class name
  2. It must not have a return type (not even void)

Types of Constructors

There are two types of constructors:

  1. The default (no-arg) constructor
  2. Parameterized constructor


1. Default (no-arg) constructor

This constructor has no parameters, and its syntax is:

nameOfTheClass() {}


Example: Creating a no-arg constructor in the Car class. It will be called at the time the object is created.

class Car {

  public Car() { // constructor
    System.out.println("The car is mooving!");
  }

  public static void main(String args[]) {
    Car car = new Car(); // with this, we are actually calling a constructor
  }
}
Output: The car is moving!
 
Note: The compiler automatically creates a default constructor if there is no constructor in the class. The purpose of having a default constructor is to provide default values of the objects.

Example:

class Printer {

  int numOfPages;
  String model;

  // no constructors defined
}

public class ConstructorExample {

  public static void main(String[] args) {

    Printer printer = new Printer(); // default constructor gets called
    System.out.println(printer.numOfPages);
    System.out.println(printer.model);

  }
}
Output: 0 null
 

2. Parameterized constructor

We use parameterized constructors to provide different values ​​to different objects of the same class.

class Printer {

  int numOfPages;
  String model;

  Printer(int numOfPages) {
    this.numOfPages = numOfPages;
  }

  Printer(int numOfPages, String model) {
    this.numOfPages = numOfPages;
    this.model = model;
  }
}

public class ConstructorExample {

  public static void main(String[] args) {

    Printer printer1 = new Printer(100); // calling first constructor
    Printer printer2 = new Printer(100, "Philips"); // calling the second constructor

    System.out.println("Printer1: numOfPages= " + printer1.numOfPages + " model=" + printer1.model);
    System.out.println("Printer2: numOfPages= " + printer2.numOfPages + " model=" + printer2.model);

  }
}


In the example above, we created two objects of the Printer class. Then, depending on the arguments, the corresponding constructor got called.

Constructor Overloading in Java

Just as we have a method overloading in Java, we can also overload constructors.

A class can have any number of constructors that differ in the parameter list. The compiler determines which constructor to call based on the number of parameters and their type.

We already had a constructor overloading in the previous example. Here is another one:

class Car {

  int maxSpeed;
  String model;
  String yearManufactured;

  Car() {
    // ...
  }

  Car(int maxSpeed) {
    // ...
  }

  Car(int maxSpeed, String model) {
    // ...
  }

  Car(int maxSpeed, String model, String yearManufactured) {
    // ...
  }
  
}

Invoking One Construct from Another

We can call one constructor from another using the keyword this and provide the corresponding arguments.

Example:

class Library {

  int numOfBookAvailable;
  String location;

  Library() {
    System.out.println("No-arg constructor...");
  }

  Library(int numOfBookAvailable) {
    this(numOfBookAvailable, "London"); // calling the third constructor
  }

  Library(int numOfBookAvailable, String location) {
    this.numOfBookAvailable = numOfBookAvailable;
    this.location = location;
  }

}


Note: a call to this() must be the first statement in the constructor body. Otherwise, we’ll get a compiler error.

Access Modifiers

Just like methods, constructors can have access modifiers. We can define private, protected, public, or default constructors in Java. Using access modifiers, we are controlling the creation of the objects.

Important Notes:

  1. Every time an object is created using the new keyword, the corresponding constructor gets called.
  2. Which constructor will be called is determined based on the arguments passed during the class instantiation.
  3. If there is no constructor in the class, the compiler automatically creates a default one.
  4. The constructor can’t have a return type. All constructors return the current object.
  5. A call to this() must be the first statement in the constructor body.

That’s it!

 

Leave a Reply

Your email address will not be published.