Class Constructor in a Class

Introduction

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.

Definition

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.

Example

Let us look into an example:

**** Class Definition****

CLASS  ZCL_DEMO DEFINITION.

PUBLIC SECTION.

METHODS:  CONSTRUCTOR.                                                         “Instance Constructor”

CLASS-METHODS: CLASS_CONSTRUCTOR.                              “Static Constructor”

END CLASS.

****Class Implementation****

CLASS  ZCL_DEMO IMPLEMENTATION.

METHOD CONSTRUCTOR.

WRITE: “Instance Constructor is initiated”.

END METHOD.

METHOD CLASS_CONSTRUCTOR.

LV_DATE = SY-DATUM.                                                                  “Changing the value of attribute”

END METHOD.

END CLASS.

START-OF-SELECTION.

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”.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.