Constructors are special methods in a class that are automatically invoked when an instance of the class is created. The main role of constructors is to initialize the instance variables of a class.
In Java, constructors share the same name as the class and don't have a return type.
Types of Constructors:
1. Default Constructor:
- A default constructor is a constructor that is automatically generated by the compiler if no constructor is explicitly defined in the class.
- It has no parameters and initializes the data members to their default values.
- The default constructor is invoked when an object is created without any arguments.
Example:
class MyClass
{
private int data;
// Default constructor (automatically generated if not defined)
public MyClass()
{
data = 0;
}
}
In the above example, the `MyClass` has a default constructor that initializes the `data` member to zero.
2. Parameterized Constructor:
- A parameterized constructor is a constructor that takes one or more parameters.
- It allows you to initialize the data members of an object with specific values provided at the time of object creation.
Example:
class Rectangle
{
private int length;
private int width;
// Parameterized constructor
public Rectangle(int len, int wid)
{
length = len;
width = wid;
}
}
In the above example, the `Rectangle` class has a parameterized constructor that takes the length and width as parameters and initializes the corresponding data members.
Constructor Overloading:
Constructor overloading refers to the ability to define multiple constructors within a class, each having a different parameter list. The compiler determines which constructor to invoke based on the arguments provided during object creation.
Example:
class Employee
{
private String name;
private int age;
private double salary;
// Default constructor
public Employee()
{
name = "";
age = 0;
salary = 0.0;
}
// Parameterized constructor with three arguments
public Employee(String newName, int newAge, double newSalary)
{
name = newName;
age = newAge;
salary = newSalary;
}
}
In the above example, the `Employee` class demonstrates constructor overloading. It has a default constructor and a parameterized constructor. These constructors allow creating `Employee` objects with different initialization options.