We have understood about constructors in our previous article, a constructor is a special method that is invoked automatically at the time object is created or instantiated. It has two types: Instance Constructor and Static Constructor. The static constructor also called as class constructor is invoked whenever there is first call to the class whether it is through an instance or class.
The class constructor has some special properties like,
- Each class has a single static constructor.
- The class constructor is called exactly once for each class.
- The method don’t have importing/ exporting parameters and cannot raise exception.
The class constructor can also be used to set default values for global attributes irrespective of the instance or methods. Also, while declaring the class constructor one must keep in mind that the name of the constructor must be CLASS_CONSTRUCTOR and declared using the statement CLASS-METHODS in the declaration part of the class.
A class constructor is a method which is automatically invoked whenever the first call to the class is made, it may be through an instance or class.
Let us look into an example:
**** Class Definition****
CLASS ZCL_DEMO DEFINITION.
METHODS: CONSTRUCTOR. “Instance Constructor”
CLASS-METHODS: CLASS_CONSTRUCTOR. “Static Constructor”
CLASS ZCL_DEMO IMPLEMENTATION.
WRITE: “Instance Constructor is initiated”.
LV_DATE = SY-DATUM. “Changing the value of attribute”
DATA: LO_DEMO TYPE REF TO ZCL_DEMO.
**Class object creation**
CREATE OBJECT LO_DEMO.
**Whenever the first call to class is made CLASS_CONSTRUCTOR is triggered
WRITE: “INSTANTIATING CLASS CONSTRUCTOR”, ZCL_DEMO=>LV_DATE.
A commonly asked question is that whether we can redefine the constructors? So, it is a big NO as the redefinition of constructors are not allowed and the program will fall into error “Constructor may not be over-defined”.