Constructors overloading in java | with example

Constructors overloading in java

 

You are already aware of Function Overloading.

Constructor Overloading in Java works exactly in the same way.

Constructor Overloading can be defined as the creation of multiple constructor objects, with the name as same as the class, but are designed to accept different data types in varying numbers as parameterized arguments.

Example:

class constover
{
int x,y;
constover()      
{
x=0;
y=0;
}
constover(int n1, int n2)
{
x=n1;
y=n2;
}
}

Here we are declaring the constructors with identical names but the parameters are different and thus they are treated as different entities.

Note:

  • Constructor methods should be declared with the same name as the name of the class in which they are declared.
  • Constructors do not need to be declared with a return type because they are used to initialize the member variables.
  • Constructors are automatically called during execution.
Constructors overloading in java | with example