Constructor
- Pronunciation
- kun-STRUK-ter
In short
A constructor is a special method that runs when a new object is created from a class, setting up its starting values so it is ready to use.
What is a constructor in programming?
A constructor is the code that runs automatically when you create a new object. Its job is to put the object into a valid starting state: storing the values passed in, setting defaults, and checking that the input makes sense. In JavaScript and TypeScript it is a method named constructor, in Python it is __init__, and in Java and C# it is a method with the same name as the class and no return type.
You rarely call a constructor by name. In JavaScript, Java and C# you write new, as in new User("Ada"), and in Python you call the class like a function, User("Ada"). The arguments go to the constructor's parameters. A class can offer several ways to build an object: Java and C# allow overloading with different parameter lists, while languages without overloading use default values or named factory methods such as User.fromJson().
A constructor is like the setup when you open a bank account: before you can use it, the bank records your name, assigns a number and sets the balance to zero. In a subclass, the constructor usually calls the parent's constructor first, with super() in JavaScript, Java and Python, so the inherited part of the object is set up too. Keeping a constructor short and free of slow work, such as network calls, makes objects easy to create and to test.
Key takeaways
- A constructor runs automatically when a new object is created from a class.
- Its job is to give the object a valid starting state.
- It is called
constructorin JavaScript,__init__in Python, and takes the class's name in Java and C#. - A subclass constructor calls the parent's constructor with
super().
Example
class Account {
constructor(owner, balance = 0) {
if (!owner) throw new Error("An account needs an owner");
this.owner = owner; // store what was passed in
this.balance = balance; // or fall back to a default
}
}
const account = new Account("Ada"); // runs the constructor
console.log(account.balance); // 0Readers ask
What is the difference between a constructor and a method?
A method is called on an object that already exists, as often as needed. A constructor runs once, while the object is being created, and its only job is to set it up. It doesn't return a value of its own, because the new object is the result.
Can a constructor be private?
Yes, in languages such as Java, C# and TypeScript. A private constructor stops other code from calling new directly, so a class can send callers through a factory method instead, or allow only one instance, as in the singleton pattern.
See also
- ClassProgramming Fundamentals, p. 9A class is a blueprint in object-oriented programming that defines the data and behavior shared by a group of objects, which are created from it as instances.
- ObjectProgramming Fundamentals, p. 39An object is a bundle of related data and behavior: values in named fields, often called properties, and functions that work on them, called methods.
- MethodProgramming Fundamentals, p. 37A method is a function that belongs to an object or class and is called on it, so it can read and change that object's data, as in user.rename("Ada").
- OOPProgramming Fundamentals, p. 40OOP, or object-oriented programming, is a way of structuring code around objects that bundle related data together with the functions that act on that data.
- InheritanceProgramming Fundamentals, p. 28Inheritance is an object-oriented programming feature that lets a new class reuse, extend, and override the fields and methods of an existing class.
- ParameterProgramming Fundamentals, p. 43A parameter is a named input in a function's definition, and an argument is the actual value passed in that place when the function is called.
- EncapsulationProgramming Fundamentals, p. 17Encapsulation is the practice of bundling data with the methods that use it and hiding internal details, so outside code works only through a public interface.
Sources
Spotted a mistake or something missing on this page?Suggest an edit