Constructor

A constructor is a special method that is invoked upon instantiation of an object and is used to provide initial values for the object being created. i.e. it sets the specified attributes to a known state.

 

It is always named exactly the same as the name of the class.

 

Has no return value.

 

Cannot be explicitly called.

 

Whenever an object is created, constructor will be called automatically, even if the programmer doesn't define a constructor the compiler will create an empty default constructor.

 

If a constructor has been defined, the compiler will not provide a default.

 

Do not include logical code in constructor, because it is only called once, when the object is instantiated

 

The constructor is defined between lines 9 to 12

 

overloading the constructor allows different parameters to be supplied to use different constructors

In this example, an overloaded constructor has been defined between lines 13 to 16, that allow us to pass in initial values when defining the object on line 25.

Leave a Reply