Appearance
Lesson 7 — Polymorphism & Method Redefinition
Polymorphism lets one reference type work with several concrete object types.
text
REF TO Product
│
├── Book object
└── Movie objectWhen a subclass redefines a method, ABAP executes the implementation belonging to the actual object.
Learning objectives
- declare redefinable superclass methods;
- use
REDEFINITIONin subclasses; - explain dynamic dispatch;
- use superclass references for subclass objects;
- create internal tables of superclass references;
- process heterogeneous objects uniformly;
- call
super->methodwhen extending superclass behavior.
1. Add a polymorphic method to Product
In ZCL_PRODUCT_BASE_### add:
abap
METHODS get_description
RETURNING VALUE(description) TYPE string.Implementation:
abap
METHOD get_description.
description = |Generic product - Price: { price }|.
ENDMETHOD.2. Redefine in Book
In ZCL_BOOK_###:
abap
METHODS get_description REDEFINITION.Implementation:
abap
METHOD get_description.
description = |Book: { title } by { author } - Price: { price }|.
ENDMETHOD.The method signature cannot be changed by the redefinition.
3. Redefine in Movie
abap
METHODS get_description REDEFINITION.Return movie-specific content.
4. Dynamic dispatch
abap
DATA item TYPE REF TO zcl_product_base_###.
item = NEW zcl_book_###( ... ).
out->write( item->get_description( ) ).Even though item is typed as Product, ABAP calls Book's redefined implementation because the actual object is a Book.
5. Reassign the same reference
abap
item = NEW zcl_movie_###( ... ).
out->write( item->get_description( ) ).Now the Movie implementation runs.
6. Table of superclass references
abap
TYPES tt_products
TYPE STANDARD TABLE OF REF TO zcl_product_base_###
WITH EMPTY KEY.Create:
abap
DATA products TYPE tt_products.
APPEND NEW zcl_book_###( ... ) TO products.
APPEND NEW zcl_movie_###( ... ) TO products.7. Polymorphic loop
abap
LOOP AT products INTO DATA(product).
out->write( product->get_description( ) ).
ENDLOOP.One loop, one method call, different implementations.
8. super->method
A redefined method can reuse superclass behavior:
abap
METHOD get_description.
DATA(base) = super->get_description( ).
description = |{ base }; Book: { title }|.
ENDMETHOD.Use this when the subclass wants to extend rather than fully replace behavior.
9. Why polymorphism matters
Without polymorphism:
text
IF object is Book ...
ELSEIF object is Movie ...With polymorphism:
text
product->get_description( )The object decides the implementation.
10. Summary
text
REDEFINITION
dynamic dispatch
superclass reference
subclass object
table of references
polymorphic loop
super->methodLesson 8 introduces interfaces: polymorphism based on a contract rather than a shared superclass.