What is a constructor in OOP?
A constructor is a special method that runs automatically when an object is created. Its job is to set the starting values of the object so it begins life in a valid state. A constructor has the same name as the class and has no return type. If you do not write one, the compiler provides a default constructor.
Why constructors exist
When you create an object you often want it to start with sensible values. A constructor lets you set those values in one place, so no object is ever created half finished. It runs once, at the moment the object is made.
class Student {
String name;
int age;
Student(String n, int a) { // constructor
name = n;
age = a;
}
}
Student s = new Student("Asha", 20); // constructor runs here
Types of constructors
- Default constructor: takes no arguments and sets default values. The compiler adds one if you write none.
- Parameterised constructor: takes arguments so you can set values while creating the object.
- Copy constructor: creates a new object by copying an existing one, common in C++.
Key rules
A constructor has the same name as the class and no return type, not even void. You can have more than one constructor in a class by giving them different parameters, which is constructor overloading.
A common follow up is the difference between a constructor and a normal method. The constructor has no return type and runs automatically on object creation, while a method has a return type and runs only when you call it. State that clearly and you look confident.
Common follow up questions
Related interview questions
Want the full OOP guide?
Read every OOP concept with notes, diagrams, and code in one place. Track your progress as you go.
Open the OOP guide All OOP questions