Constructors
medium 45 minA constructor turns fresh, empty memory into an object that is ready to use.
Video lesson · Chapter 1 of 6
Make a prediction
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
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
newanddelete.2001
Python 2.2 (PEP 253) separates
__new__, which makes the object, from__init__, which fills it.2018
Python 3.7 brings dataclasses (PEP 557, written in 2017):
__init__is generated from the fields.2025
Java 25 allows statements before
super(...)andthis(...)(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.
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.
Frames 1 to 5 are construction. The last three are the questions interviewers add: invalid input, names, copies.
First look
One class, one door
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)self is the new object. Left of = is its field, right is the argument.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
newcalls 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
| Constructor | Method | |
|---|---|---|
| Name | That of the class (or __init__, constructor) | Any |
| Return type | None | Needed (a type or void) |
| Call | By creating an object | By name, as often as you like |
| Inheritance | Not 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::Base | Inherited |
| Overriding | No. Each class builds its own part | Yes |
| Job | Make a valid object | Use or change a valid object |
Under the hood
What new really does
From the call to the reference
What is in memory after two calls
1/3The class
It says which fields a house has and how one is made. It holds no values and no house.
usesdepends on
House h(...) is the object itself, without a reference.Kinds
Five constructors to know
| Kind | Looks like | Use | Watch out |
|---|---|---|---|
| Default | Person() | A sensible empty object | Java and C++ stop generating it once you write any other |
| Parameterized | Person(name, age) | The usual one | Many parameters of the same type get swapped |
| Copy | Person(Person other) | An independent twin | Nested lists must be copied as well |
| Move (C++) | Person(Person&& other) | Take the buffers of a dying object | The old one is valid but empty or unknown. Mark it noexcept |
| Private | private Database() | Factory, one instance, only static helpers | Reflection can still reach it in Java |
Does the compiler write a constructor for me?
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
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
| Language | Parent call | If you leave it out |
|---|---|---|
| Java up to 24 | Must be the first statement | The compiler adds super(). It fails if the parent has no such constructor |
| Java 25 | Statements that do not use the new object may come before it | The same |
| C++ | In the initializer list: : Person(name, age) | The parent's default constructor is used |
| Python | super().__init__(...), anywhere | The parent's part is simply not set |
| JavaScript, TypeScript | super(...) before the first use of this | An 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
| Pattern | Sketch | More |
|---|---|---|
| Telescoping | Person(n) { this(n, 0); } | This page, FAANG interview |
| Builder | Person.builder().name("Asha").age(30).build() | Builder |
| Factory method | Person.guest(), Person.fromJson(text) | Factory method |
Everyday
What different objects need at birth
| Object | Takes | Sets or checks | Does not do |
|---|---|---|---|
| Shopping cart | User id | Starts with an empty list of its own | Load prices |
| Database client | Config or a ready pool | Checks host and timeout | Connect. connect() or a factory does |
| Email client | Server settings and a transport | Checks the sender address | Send a test mail |
| Game character | Name, class of character, position | Starting stats from a table, position inside the map | Draw 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.
newreserves, 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
- Bjarne Stroustrup: A History of C++, 1979-1991
- JEP 513: Flexible Constructor Bodies
- Java language specification: classes and constructors
- C++ Core Guidelines: constructors (C.40 to C.52, C.82)
- ISO C++ FAQ: constructors
- PEP 253: subtyping built-in types
- PEP 557: data classes
- MDN: super
- TypeScript handbook: classes, initialization order
- Integer.valueOf
- Django: creating objects
- Spring: constructor and setter injection
- Effective Go: constructors and composite literals
- Rust API guidelines: predictability