A constructor is a special dedicated method to initialize a new instance of a class. The constructor method for a class will have the same name as the class. A class can contain more than one constructor method, but each having a different set of parameters. They are called overloaded constructor methods.

A constructor method is the first method that’s called and executed when a new object is instantiated. It’s primary usage is to assign default values to variables, do basic cleanup or calculation, etc. A constructor method is not a mandatory method. A programmer can create it if needed.

If a class does not contain a user-defined constructor, then the compiler initialized member variables of that class to default values.
Ex: An integer is set to 0 (zero), string is set to NULL, etc.

There are 3 basic rules that every constructor method in a class must follow:

  1. A constructor should have the same name as that of the class in which it is created.
  2. A constructor cannot specify a return value type. Not even void.
  3. If more than one constructor is created within a same class, each constructor should have a different set of parameters.

Constructor Example

This example shows a class and a constructor named Circle:

public class Circle {
          public int x = 0;
          public int y = 0;
          public int radius = 0;

          public Circle(int x, int y, int radius) {
                    this.x = x;
                    this.y = y;
                    this.radius = radius;
          }
}

A no-argument constructor is a constructor which does not take any arguments. In overload constructors, every constructor must have a different number of parameters or their types should vary. The compiler will give an error if this rule isn’t met.

Constructor Inheritance

In case of inheritance where a class is inherited from another class, the constructors of parent class are also inherited. However, a constructor of a parent class can be overridden in the child class.

Therefore, the child class constructor will be called when an object is instantiated. If you desire to call the constructor of parent class also during instantiation, you will need to call it using the keywordsuper from within the child constructor.

Ex: super Circle( 4, 5, 6 );

The super statement should be the first line of code in the child constructor.