Constructors
medium 45 minA constructor turns fresh, empty memory into an object that is ready to use.
Watch lesson4:45
Where it shows up
The same pattern appears across everyday software.
Java Integer.valueOf
The documentation calls the static factory generally a better choice than the constructor, because it caches: values from -128 to 127 always come from the cache. The constructor is deprecated for removal.
Java List.of and List.copyOf
Static factories that return unmodifiable lists. The caller names what they want and never sees which class it is.
Python datetime
The documentation lists `today`, `fromtimestamp` and others as other constructors, all class methods. `date(...)` itself raises ValueError for a day that does not exist.
Django models
The documentation advises against overriding `__init__` on a model, because a changed signature may prevent saving. It suggests a classmethod or a method on a manager.
Spring
The Spring team generally advocates constructor injection: components can be immutable, dependencies are not null, and callers always get a fully initialized object.
Kotlin
The primary constructor is part of the class header, and `init` blocks hold the checks. Default values replace most overloads.
Go
Has no constructors. Effective Go shows functions such as `NewFile` for when the zero value is not good enough.
Rust
Constructors are only a convention. The API guidelines ask for static methods such as `new`, with names that say more where needed.
PyTorch
A module must call `super().__init__()` first. Assigning a buffer earlier raises cannot assign buffer before Module.__init__() call, instead of failing much later.