Constructors are special methods in Java that are used to initialize objects when they are created. A constructor is automatically invoked when an object is instantiated and helps assign initial values to object properties.
Key Points: • A constructor has the same name as the class. • It does not have a return type, not even void. • Constructors are automatically called when an object is created using the new keyword. • Java supports default constructors and parameterized constructors. • Constructors can be overloaded to initialize objects in different ways.
Example: When creating a Student object, a constructor can initialize properties such as name and age at the time of object creation.
Code Example:
class Student {
String name;
Student(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student("Amol");
System.out.println(student.name);
}
}Interview Tip: A concise interview answer is:
"A constructor is a special method used to initialize an object. It has the same name as the class, does not have a return type, and is automatically called when an object is created."