Preface – This post is part of the SAP ABAP OData Tutorial series.
Before discussing the difference between Constructor and Class Constructor, let’s have a short introduction of the two.
Table of Contents
Constructors are a special type of method in a class that is called automatically by the system to set the initial state of a new object or the class. They cannot be called using the CALL METHOD statement. The constructors are always present in a class but to implement a constructor it must be declared explicitly with the METHODS or CLASS-METHODS statements.
There are two types of constructors: Instance constructor and Static Constructor.
The predefined method CONSTRUCTOR is an instance constructor of the class. This instance constructor is automatically called when an instance of the class is created. Its signature can have only importing parameters or exceptions. Since it is an instance method, it can access all the attributes of the class.
Syntax to declare :
METHODS : constructor.
The predefined method CLASS_CONSTRUCTOR is a static constructor of the class and is automatically called when the components of the class are accessed for the first time. Its signature cannot have importing parameter or exceptions. It is called once for each class irrespective of the instance created.
Syntax to declare :
CLASS-METHODS : class_constructor.
Now, let’s have a look at their difference.
Differences between Constructor and Class Constructor
|It is executed automatically whenever an object is created or instantiated.||It is executed automatically whenever the first call to the class is made.|
|It is called once for each instance.||It is called only once for each class and internal session.|
|It is declared using METHODS statement.||It is declared using CLASS-METHOD statement.|
|It has only Importing Parameters.||It has no Importing and Exporting Parameters.|
|It can raise exception.||It cannot raise exception.|
|It is an Instance method.||It is a static method.|
|It can access all attributes of a class.||It can access only static attributes of a class.|