Custom Search

Java: Constructor

A constructor is a special method that is used to initialize a newly created object and is called just after the memory is allocated for the object

It should be used to initialize objects default values when an object is created.

It is not mandatory for the coder to write a constructor for the class but it is good practice to do so, as it makes you think about the default values..

If no user defined constructor is provided for a class, the compiler initializes member variables to its default values.

  • numeric data types are set to 0
  • char data types are set to null character('\0')
  • reference variables are set to null

When you create a Constructor you should observe the following rules:

  • It must have the same name as the class of the objects it initialises.
  • It should not return a value - not even void

Constructor overloading

Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the list and their type

Examples of valid constructors for class Example are:

  • Example(int a);
  • Example (int a,int b);
  • Example(String a,int b);


Constructor chaining

Consider a scenario where a base class is extended by a child class.
Whenever an object of the child class is created, the constructor of the parent class is invoked first.
This is called Constructor chaining.