This is a type of CONSTRUCTOR, this method is executed whenever a first call to the class is made, the call may be through instance or through class name.
These are also called as STATIC CONSTRUCTORS, the name must be CLASS_CONSTRUCTOR.
Example: We will add a class constructor to make default material type as 'FERT'(Finished Product)
Follow the below steps to create a class constructor.
Go to SE24, provide the class name ZCL_SAPN_MATERIALS, click on change.
Go to attributes tab and add an attribute to make default material type.
Go to methods and add a method name CLASS_CONSTRUCTOR as below.
We can not add any exporting and importing parameters to a CLASS_CONSTRUCTOR method.Double click on the method CLASS_CONSTRUCTOR and add below code.
METHOD CLASS_CONSTRUCTOR. *Set default material type as FERT MAT_TYPE = 'FERT'. ENDMETHOD.Here we take a small example to test this one.The below on is a simple example and explains you a lot.
REPORT ZSAPN_CLASS_CONSTRUCTOR. DATA : LO_MATERIAL TYPE REF TO ZCL_SAPN_MATERIALS. "Declare class CREATE OBJECT LO_MATERIAL "create object CONSTRUCTOR method will trigger EXPORTING IM_SPRAS = 'E'. **When ever first call to a class is made class constructor will trigger WRITE:/ 'Executed through class constructor', ZCL_SAPN_MATERIALS=>MAT_TYPE. "Executed through Class Constructor WRITE:/ 'Executed through Constructor', LO_MATERIAL->LANGUAGE . "Executed through constructor method