Wednesday, September 5, 2018

modify constructor in sub class


   SIMPLE EXAMPLE TO SHOW THAT  SUB CLASS CAN MODIFY CONSTRUCTOR OF SUPER CLASS.

In this example , i have taken simple 3 classes , and constructor , if i want to add functionality to constructor we could do it in child class.

Each class has an instance constructor called constructor. This is an exception to the rule that states that component names along a path in an inheritance tree must be unique. The instance constructors of the various classes in an inheritance tree, however, are fully independent of one another. 

Constructor of the super class has to be called by using CALL METHOD SUPER->CONSTRUCTOR statement inside the implementation in sub classes.

NOTE:We cannot constructor like method , it would give an error.(You cannot call the special method 'CONSTRUCTOR' directly) .



*&---------------------------------------------------------------------*
*& Report  ZSR_CONSTRUCTORINHERITANCE
*&
*&---------------------------------------------------------------------*
*&
*&
*&---------------------------------------------------------------------*

REPORT  ZSR_CONSTRUCTORINHERITANCE.

CLASS GRAND_FATHER DEFINITION.
PUBLIC SECTION.
DATAV_VAL1 TYPE CHAR40.
METHODS CONSTRUCTOR.
ENDCLASS.

CLASS GRAND_FATHER IMPLEMENTATION.
METHOD CONSTRUCTOR.
V_VAL1 'HI I AM FROM GRAND FATHER CLASS'.
WRITE/5 V_VAL1.
ENDMETHOD.
ENDCLASS.


CLASS FATHER DEFINITION INHERITING FROM GRAND_FATHER.
PUBLIC SECTION.
METHODS  CONSTRUCTOR.
ENDCLASS.

CLASS FATHER IMPLEMENTATION.
METHOD CONSTRUCTOR .
CALL METHOD SUPER->CONSTRUCTOR.
V_VAL1 ' HI I AM PARENT CLASS'.
WRITE:/5 V_VAL1.
ENDMETHOD.
ENDCLASS.


CLASS CHILD DEFINITION INHERITING FROM FATHER.
PUBLIC SECTION.
DATA:V_VAL3 TYPE CHAR40.
METHODS CONSTRUCTOR.
ENDCLASS.

CLASS CHILD   IMPLEMENTATION.
METHOD CONSTRUCTOR.
CALL METHOD SUPER->CONSTRUCTOR.
*CALL METHOD SUPER->
V_VAL1 ' HI I AM FROM GRAND CHILD CLASS'.
SKIP 2.
V_VAL3 'HI I AM THE NEW CREATED FROM GRAND CHILD CLASS'.
WRITE/5 V_VAL1,V_VAL3 .
ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
DATAOBJ1 TYPE REF TO CHILD.
CREATE OBJECT OBJ1.

-------------------------output:----------------------------------------