constructor

The special method that runs when a new object is created from a class and sets up its starting data.

In more detail

A constructor gives the object's fields their starting values and can reject invalid input before the object exists; in Python it is the __init__ method. Passing collaborators into the constructor, rather than building them inside it, is how dependency injection works and lets tests supply doubles.

Examples

Java: a constructor has the class's name and no return type; if you write none, javac adds an empty default one.
public Greeter(String name) { this.name = name; }

Related terms

Taught in

References

Certification courses