A constructor is a special method that runs automatically when an object is created, used to set up the object's initial state. It typically has the same name as the class (or a reserved name like __construct in PHP or __init__ in Python) and no return type.
class Rectangle {
width
height
function __construct(width, height) {
this.width = width
this.height = height
}
function area() {
return this.width * this.height
}
}
rect = new Rectangle(4, 5) // constructor runs immediately, setting width=4, height=5
print(rect.area()) // 20
Constructors ensure an object can never exist in an incomplete or invalid state — by requiring certain parameters up front, you make it impossible to accidentally create a Rectangle with no dimensions at all.
Constructor chaining in inheritance: a subclass constructor typically needs to call its parent's constructor to ensure inherited properties are also properly initialized:
class Shape {
function __construct(color) { this.color = color }
}
class Rectangle extends Shape {
function __construct(color, width, height) {
super(color) // calls Shape's constructor first
this.width = width
this.height = height
}
}
Default constructors: most languages provide an implicit, empty constructor if you don't define one yourself. Multiple constructors (constructor overloading) are supported in some languages (Java, C++, C#) to allow creating objects in different ways; others (PHP, Python) achieve similar flexibility with default parameter values or static factory methods instead.