Constructors
In this lesson, the world of constructors is explored and you'll learn why they are necessary for creating a class.
We'll cover the following
What Is a Constructor?
A constructor is a method that is called to create an instance or object of a class.
As the name suggests, the constructor is used to construct the object of a class. It is a special method that outlines the steps that are performed when an instance of a class is created in the program.
A constructor’s name must be exactly the same as the name of its class.
We have already discussed that to model the state of an object we declare member variables or fields in a class.
The intention of implementing a constructor is to put an object in a predictable initial state, i.e., to initialize some or all the fields of a class to values that can be specified by the user of the class. A constructor does not have a return type. Not even void
! It is a good practice to declare/define it as the first member method.
Let’s study the different types of constructors and use them to create class objects.
Default Constructor
The default constructor is the most basic form of a constructor. It is called default because when we don’t implement a constructor in our class, the compiler, by-default implements one for us at compile time which initializes the fields of that class to their default values. Think of it this way:
When there is no constructor implemented in a class, a default constructor is always implemented by the compiler automatically. When called, it creates an object in which the fields are initialized to their default values.
This will make sense when we look at the code below. Here, we have our VendingMachine
class, with its default constructor, and we’ll create an object out of it in our Main()
method:
Get hands-on with 1400+ tech skills courses.