A constructor is a special member of a class that is automatically invoked when an object is created. Its primary purpose is to initialize the object's state and assign initial values to its fields. A constructor has the same name as the class and does not have a return type, not even void.
Key Points: • A constructor is called automatically when an object is created using the new keyword. • It is used to initialize object variables and prepare the object for use. • The constructor name must be the same as the class name. • Constructors do not have a return type. • Java supports both default constructors and parameterized constructors. • A class can have multiple constructors through constructor overloading.
Example: When creating an Employee object, a constructor can initialize the employee's name and salary at the time of object creation instead of setting them later.
Code Example:
public class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public void display() {
System.out.println("Employee Name: " + name);
}
public static void main(String[] args) {
Employee emp = new Employee("Amol");
emp.display();
}
}Output:
Employee Name: Amol
Types of Constructors:
1. Default Constructor • No parameters • Initializes objects with default values
2. Parameterized Constructor • Accepts parameters • Initializes objects with custom values
Interview Tip: A concise interview answer is:
"A constructor is a special method-like member of a class that is automatically executed when an object is created. It is used to initialize the object's state, has the same name as the class, and does not have any return type."