EMZETT.
Login

Constructors

In short: A special method that’s automatically called when a new object of a class is created — usually used to set the initial values of the fields.

In more detail: A constructor usually carries the same name as the class and has no return type (not even void). Via overloading, a class can offer several constructors with different parameter lists, such as one with no arguments (default values) and one that sets all fields directly at creation.

In Depth

class Person {
    name
    age
 
    Constructor(name, age) {
        this.name = name
        this.age = age
    }
}
 
p = new Person("Alex", 30)   // automatically calls the constructor

If a class doesn’t define its own constructor, the compiler/interpreter in many languages automatically provides an invisible “default constructor” with no parameters, which simply does nothing besides creating the object. But once you define ONE custom constructor, this automatic default constructor disappears in most languages (e.g. Java) — if you still want to be able to create the object with no arguments, you have to explicitly provide that case yourself as well.

A related concept in many languages is constructor chaining: a constructor can call another, more detailed constructor of the same class, to avoid writing code twice:

class Person {
    Constructor(name) {
        Constructor(name, 0)   // also calls the second constructor
    }
    Constructor(name, age) {
        this.name = name
        this.age = age
    }
}

Unlike a normal method, a constructor can’t be called “later” — it’s guaranteed to run exactly once, at the moment of object creation, and an object practically never exists in the program without its constructor having run. This makes it the ideal place to ensure invariants meant to hold for the entire remaining life of the object (see Encapsulation).

See also: Classes, Objects, this Keyword