AlgoViz

Constructors

medium 45 min

A constructor turns fresh, empty memory into an object that is ready to use.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:45

Constructors

1:03Reel

Theory

Read or listen first. About 2 min.

What it is

A constructor is the code that runs when an object is created. It takes the arguments, checks them and sets every field. After it has finished, the object is valid and may be used.

In Java, C++ and C# it has the same name as the class and no return type, not even void. Python uses __init__, JavaScript and TypeScript use the word constructor. In all of them it is called for you: new Person("Asha") in Java, Person("Asha") in Python.

The constructor does not allocate the memory. new (or Python's __new__) does that first. The constructor then fills what it was given.

Why it exists

Without a constructor, each caller must remember to set every field in the right order. One forgotten field is a bug that shows up far away from where it was made.

With one, there is a single door into the class. Checks at that door hold for every object that exists: a person has a name, a range has its start before its end. Such a rule is called an invariant, and the constructor establishes it.

It is also the honest list of what a class needs. A reader learns from the parameters what the object depends on, and a test knows what to hand in.

A short history

  1. 1980

    The first version of C with Classes, later C++, already has constructors and destructors. Bjarne Stroustrup's history paper (A History of C++: 1979-1991) shows them written as functions called new and delete.

  2. 2001

    Python 2.2 (PEP 253) separates __new__, which makes the object, from __init__, which fills it.

  3. 2018

    Python 3.7 brings dataclasses (PEP 557, written in 2017): __init__ is generated from the fields.

  4. 2025

    Java 25 allows statements before super(...) and this(...) (JEP 513, Flexible Constructor Bodies), after previews in Java 22, 23 and 24. The rule that the call must come first is history there.

Words to know

Constructor
Code that runs at creation and makes the object valid.
Invariant
A rule that is true for the object's whole life.
Default constructor
One that can be called without arguments. Java and C++ write one for you only if you wrote none.
Parameterized constructor
One that takes values.
Copy constructor
Makes a new object from an existing one of the same class.
Move constructor
C++: takes over the insides of an object that is no longer needed.
Private constructor
Only code inside the class can call it.
Overloading
Several constructors with different parameter lists.
Chaining
One constructor calls another: this(...) in the same class, super(...) in the parent.
Static factory
A named method that returns an object, such as Person.guest().
Telescoping
A row of constructors, each with one parameter more than the last.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 4

Reserve. new finds memory for the object

Understand it

Start here

Nothing half built goes into the field

Asha grows corn and wants a scarecrow. Lee builds them. Watch what Lee does before saying that it is ready, and what Lee refuses to do.

The scarecrow on order
ORDERstraw hatred coatsmile

Frames 1 to 5 are construction. The last three are the questions interviewers add: invalid input, names, copies.

First look

One class, one door

Python
class House:    def __init__(self, color, doors, windows, floors, roof):        if doors < 1:            raise ValueError("a house needs a door")        self.color = color        self.doors = doors        self.windows = windows        self.floors = floors        self.roof = roofmy_house = House("blue", 2, 4, 2, "peaked")your_house = House("red", 1, 3, 1, "flat")print(my_house.color, your_house.color)      # blue red: one class, independent objectsalias = my_house                             # no new house: a second name for the same oneprint(alias is my_house, my_house is your_house)
The smallest useful constructor. self is the new object. Left of = is its field, right is the argument.
Edit and run it in your browser

Four facts about constructors

  • Same name

    Java, C++ and C#: the constructor is named like the class. Python: __init__. JavaScript: constructor.

  • No return type

    Write void Person() in Java and you have an ordinary method that nobody calls.

  • Called for you

    new calls it exactly once per object. You cannot run it again on a finished object in Java or C++. In Python you can, and should not.

  • May be overloaded

    Java, C++ and C# allow several parameter lists. Python and JavaScript have one constructor with default values.

Constructor and method

ConstructorMethod
NameThat of the class (or __init__, constructor)Any
Return typeNoneNeeded (a type or void)
CallBy creating an objectBy name, as often as you like
InheritanceNot inherited in Java and C#. In Python and JavaScript the parent's is used if you write none. C++ can ask for it: using Base::BaseInherited
OverridingNo. Each class builds its own partYes
JobMake a valid objectUse or change a valid object

Under the hood

What new really does

From the call to the reference

Java's order. The reference reaches the caller last. Fields have default values between reserving and filling.

What is in memory after two calls

HousecolordoorsroofHouse(color, doors, roof)paint(color)

1/3The class

It says which fields a house has and how one is made. It holds no values and no house.

usesdepends on

Addresses are examples. Three fields are shown. In C++ a local House h(...) is the object itself, without a reference.

Kinds

Five constructors to know

KindLooks likeUseWatch out
DefaultPerson()A sensible empty objectJava and C++ stop generating it once you write any other
ParameterizedPerson(name, age)The usual oneMany parameters of the same type get swapped
CopyPerson(Person other)An independent twinNested lists must be copied as well
Move (C++)Person(Person&& other)Take the buffers of a dying objectThe old one is valid but empty or unknown. Mark it noexcept
Privateprivate Database()Factory, one instance, only static helpersReflection can still reach it in Java
One instance only: Singleton. Copying in depth: Prototype.

Does the compiler write a constructor for me?

In C++ give members a value where you declare them: int age = 0;. Reading an uninitialized int is an error that may look random.

Belongs in a constructor

  • Checking arguments
  • Setting every field
  • Copying lists that the caller could change later
  • Cheap values worked out from the arguments

Does not belong there

  • Network or disk, and anything you must wait for
  • Starting threads or registering listeners with this
  • Calling methods that a subclass can replace
  • Creating the database it needs: take it as an argument

Chaining

this and super

Java
class Person {    private final String name;    private final int age;    Person(String name) { this(name, 0); }          // one place does the work    Person(String name, int age) {        if (name.isBlank()) throw new IllegalArgumentException("name is empty");        this.name = name;        this.age = age;    }}class Employee extends Person {    private final String id;    Employee(String name, int age, String id) {        super(name, age);                           // the parent's part comes first        this.id = id;    }}
this(...) sends to another constructor of the same class. super(...) to one of the parent. A constructor has at most one of the two.

The rules, per language

LanguageParent callIf you leave it out
Java up to 24Must be the first statementThe compiler adds super(). It fails if the parent has no such constructor
Java 25Statements that do not use the new object may come before itThe same
C++In the initializer list: : Person(name, age)The parent's default constructor is used
Pythonsuper().__init__(...), anywhereThe parent's part is simply not set
JavaScript, TypeScriptsuper(...) before the first use of thisAn error when the object is created

Choices

Constructor, factory or builder

How should callers create it?

Booking has a room, a start and an end, and five optional extras. How do callers make one?

BreaksEmpty constructor and eight setters
How
b = new Booking(); b.setRoom(...); ...
Limit
Between the calls the object is invalid, and nobody knows when it is finished. It can never be immutable.
Choose when
Only where a framework demands it, at the edge.
WorksTelescoping constructors
How
Three parameters, then four, then five, each calling the next.
Limit
Callers count commas. new Booking(r, s, e, true, false, null, 2) tells a reader nothing.
Choose when
One or two optional values.
StrongRequired in the constructor, the rest named
How
Python and Kotlin: keyword arguments. Java: a builder whose build() calls one private constructor that checks everything.
Limit
A builder is another class to keep up to date.
Choose when
Four or more optional values, or a rule that spans several of them.

Three patterns around constructors

PatternSketchMore
TelescopingPerson(n) { this(n, 0); }This page, FAANG interview
BuilderPerson.builder().name("Asha").age(30).build()Builder
Factory methodPerson.guest(), Person.fromJson(text)Factory method

Everyday

What different objects need at birth

ObjectTakesSets or checksDoes not do
Shopping cartUser idStarts with an empty list of its ownLoad prices
Database clientConfig or a ready poolChecks host and timeoutConnect. connect() or a factory does
Email clientServer settings and a transportChecks the sender addressSend a test mail
Game characterName, class of character, positionStarting stats from a table, position inside the mapDraw itself

Summary

The whole topic in one minute.

new reserves memory, the parent part is built, then this class's fields. The reference goes to the caller only at the end. Until then nobody else should see the object.

Check arguments, set every field, copy what can change, and stop. No network, no calls to methods that a subclass may replace, no handing out this.

If it cannot build a valid object, it throws, and it releases what it had already taken. If creation needs a name, a wait or a cached result, put a factory in front.

  • new reserves, the constructor fills. The caller sees the object only when it is finished.
  • Establish the invariant: check first, then set every field, or throw.
  • The parent's part is built before the child's.
  • Never call a method that a subclass may replace, and never hand out this.
  • Copy what the caller could change later.
  • Names, waiting, caching: a static factory. Many optional values: named arguments or a builder.

Sources