Method overriding allows a subclass to provide a new implementation of a method that is already defined in the superclass. The method in the subclass must use the REDEFINITION keyword.
When to use it:
-
When a general method in a parent class needs to be customized for specific child behavior.
-
To implement polymorphism (different behavior for the same method call).
CLASS cl_parent DEFINITION.
PUBLIC SECTION.
METHODS: display.
ENDCLASS.
CLASS cl_parent IMPLEMENTATION.
METHOD display.
WRITE: 'Parent class method'.
ENDMETHOD.
ENDCLASS.
CLASS cl_child DEFINITION INHERITING FROM cl_parent.
PUBLIC SECTION.
METHODS: display REDEFINITION.
ENDCLASS.
CLASS cl_child IMPLEMENTATION.
METHOD display.
WRITE: 'Child class method - overridden'.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
DATA(lo_obj) = NEW cl_child( ).
lo_obj->display( ).
OutPut: