Constructor is a method used to initialize the attributes of the class.
Key Point:
1. It will be called automatically whenever an object is created.
2. Constructor always declared in the public section of the class.
3. Constructor doesn't return any value.
There are 2 types of constructor
Static Constructor:
It is declared using the 'class_constructor' keyword.
It cannot contain any parameters and exceptions.
Instance Constructor:
It is declared using 'constructor' keyword.
They can contain only importing parameters and exceptions.
Instance Constructor demo program:
CLASS cl_main DEFINITION.
PUBLIC SECTION.
DATA: empnum TYPE i,
empname TYPE char10.
METHODS: constructor, "instance constructor
display.
ENDCLASS.
CLASS cl_main IMPLEMENTATION.
METHOD constructor.
empnum = '10'.
empname = 'Amit'.
ENDMETHOD.
METHOD display.
WRITE:/ empnum, empname.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
DATA ob TYPE REF TO cl_main.
CREATE OBJECT ob.
CALL METHOD ob->display.
Static Constructor Demo Program:
CLASS cl_main DEFINITION.
PUBLIC SECTION.
CLASS-DATA: empnum TYPE i,
empname TYPE char10.
CLASS-METHODS: class_constructor,
display.
ENDCLASS.
CLASS cl_main IMPLEMENTATION.
METHOD class_constructor.
empnum = '10'.
empname = 'Amit'.
ENDMETHOD.
METHOD display.
WRITE:/ empnum, empname.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
CALL METHOD cl_main=>display.
Key Point:
1. It will be called automatically whenever an object is created.
2. Constructor always declared in the public section of the class.
3. Constructor doesn't return any value.
There are 2 types of constructor
Static Constructor:
It is declared using the 'class_constructor' keyword.
It cannot contain any parameters and exceptions.
Instance Constructor:
It is declared using 'constructor' keyword.
They can contain only importing parameters and exceptions.
Instance Constructor demo program:
CLASS cl_main DEFINITION.
PUBLIC SECTION.
DATA: empnum TYPE i,
empname TYPE char10.
METHODS: constructor, "instance constructor
display.
ENDCLASS.
CLASS cl_main IMPLEMENTATION.
METHOD constructor.
empnum = '10'.
empname = 'Amit'.
ENDMETHOD.
METHOD display.
WRITE:/ empnum, empname.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
DATA ob TYPE REF TO cl_main.
CREATE OBJECT ob.
CALL METHOD ob->display.
Static Constructor Demo Program:
CLASS cl_main DEFINITION.
PUBLIC SECTION.
CLASS-DATA: empnum TYPE i,
empname TYPE char10.
CLASS-METHODS: class_constructor,
display.
ENDCLASS.
CLASS cl_main IMPLEMENTATION.
METHOD class_constructor.
empnum = '10'.
empname = 'Amit'.
ENDMETHOD.
METHOD display.
WRITE:/ empnum, empname.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
CALL METHOD cl_main=>display.
Try this code in your computer for better understanding. Enjoy the code. If you have any Question you can contact us or mail us. We will reply you as soon as possible.
Post a Comment