Polymorphism allows different classes to be treated through a common parent reference, while still calling their own version of a method at runtime.
- When to use it:
When you want to treat multiple objects generically, but still get their specific behavior. - In frameworks or handlers where object types may vary.
- In real-world modeling (e.g., Animal → Dog/Cat).
- Key Notes:
Requires inheritance and method overriding. - Achieved using parent class references or interfaces.
- Great for writing extensible and clean code.
REPORT zrep_lclclass.
CLASS cl_animal DEFINITION.
PUBLIC SECTION.
METHODS: speak.
ENDCLASS.
CLASS cl_animal IMPLEMENTATION.
METHOD speak.
WRITE: 'Animal sound'.
ENDMETHOD.
ENDCLASS.
CLASS cl_dog DEFINITION INHERITING FROM cl_animal.
PUBLIC SECTION.
METHODS: speak REDEFINITION.
ENDCLASS.
CLASS cl_dog IMPLEMENTATION.
METHOD speak.
WRITE: 'Dog barks'.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
DATA: lo_animal TYPE REF TO cl_animal.
lo_animal = NEW cl_dog( ).
lo_animal->speak( ). " Outputs: Dog barks (runtime polymorphism)
Output: