Preface – This post is part of the SAP ABAP OData Tutorial series.
Table of Contents
Focusing on the concept of the constructors in a class, we will discuss what is a constructor and its type with an example. So, a constructor can be understood as a special method in a class that is automatically called when an object is created. It does not require any explicit method call.
A constructor is a special method in a class that is invoked at the time object is created or instantiated.
Type of Constructors
Constructors are of two types:
- Instance constructor
- Static constructor
The instance constructor is the predefined instance method of the class called constructor. There are few points to consider while declaring the constructor. They are:
- The name of the constructor method, irrespective of the class name or type, must be always CONSTRUCTOR.
- It is declared using a method statement in the visibility section of the class.
- The method signature can only have importing parameters or exceptions. There are no exporting parameters included.
- The instance method can be used to set default values in the class.
- The instance method anyhow can access both instance as well as static variables.
- It is called each time the object is created.
The static constructor is the predefined static method of the class called as class_constructor. There are few points to consider while declaring the static constructor. They are:
- The name of the class_constructor method must be CLASS_CONSTRUCTOR.
- It is declared using CLASS_METHODS statement in the public section of class.
- The method signature cannot contain importing or exporting parameters or exceptions.
- The static method can be used to set default values globally.
- The static method can only access the static variables.
- It is called exactly once before the class is accessed for the first time.
Let’s spot one simple example:
CLASS demo DEFINITION. PUBLIC SECTION. METHODS: CONSTRUCTOR. “Instance Constructor” CLASS_METHODS: CLASS_CONSTRUCTOR. “Static Constructor” END CLASS. CLASS demo IMPLEMENTATION. METHOD CONSTRUCTOR. WRITE: “Instance Constructor is initiated”. END METHOD. METHOD CLASS_CONSTRUCTOR. WRITE: “Static Constructor is initiated”. END METHOD. END CLASS. **class object creation** DATA: demo_obj TYPE REF TO demo. CREATE OBJECT demo_obj.
Static Constructor is initiated
Instance Constructor is initiated
In the definition part of the class, the CONSTRUCTOR is the instance constructor defined using Methods and static constructer is defined as CLASS_CONSTRUCTOR using class_methods. And their implementations are given the IMPLEMENTATION part. When the object demo_obj is created, the instance and static constructor is called.
As we can see that the output displays static constructer implementation before the instance constructor, this is because the CLASS_CONSTRUCTOR method is triggered before the CONSTRUCTOR method.