Constructors
In object-oriented programming, a constructor is a special method within a class that is used to initialize and create objects of that class. It is called automatically when an instance of the class is created. Constructors have the same name as the class they belong to and can have parameters to accept values that are necessary for object initialization.
The constructor is called when an object of a class is created
It can be used to set initial values for object attributes
Constructors are called automatically with the new keyword
Why do we need a constructor ?
When you create an object, the constructor is called automatically (Automatic initialisation)
Avoids repetition
Without a constructor, every time you make a new object, you must call a separate method to set each variable one by one
By defining constructors as part of the class, the object's creation and initialization logic are kept within the class's scope, promoting encapsulation and information hiding.
How constructor works?
It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.
Top comments (0)