SAP ABAP : OOPS Concept - Polymorphism

The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.

Real life example of polymorphism: A person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. So the same person posses different behavior in different situations. This is called polymorphism.

Polymorphism is considered one of the important features of Object-Oriented Programming. Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to define one interface and have multiple implementations. The word “poly” means many and “morphs” means forms, So it means many forms.


Polymorphism can be achieved using method overriding(Inherit ).


Example :


REPORT ztest_demo_sup.
class lcl_animal DEFINITION"class declaration
  PUBLIC SECTION"access modifier
   DATA name TYPE char10."attributes
   CLASS-METHODS class_constructor.
   METHODS constructor IMPORTING name1 TYPE char10.
   METHODS m_eat "behaviours instance method
   METHODSm_bark.
ENDCLASS.
CLASS lcl_pets  DEFINITION INHERITING FROM lcl_animal.
  PUBLIC SECTION.
  DATA pet_name TYPE char10.
  METHODS constructor IMPORTING name TYPE char10.
  METHODS m_eat REDEFINITION.
ENDCLASS.
DATA lv_dog TYPE REF TO lcl_animal"declaring object of class

START-OF-SELECTION.
"there is two way to create object of class after release 7.4
CREATE OBJECT lv_dog EXPORTING name1 'Milo'"or

DATA(lv_catNEW lcl_animalname1 'Kitty')."incline declaration with New keyword "supported only release after 7.4 ve
DATA(lv_snakeNEW lcl_petsname 'Cobra' ).
lv_dog->m_eat).
lv_cat->m_eat)."to access instance method we have to create the object of the class

lv_snake->m_eat)."child class
CLASS lcl_animal IMPLEMENTATION.
  METHOD class_constructor.
*    WRITE : / ' Super hello'.
  ENDMETHOD.
  METHOD constructor.
    name name1.
    WRITE / name.
  ENDMETHOD.
  METHOD m_eat.
    WRITE / name ,'is eating'.
  ENDMETHOD.
  METHOD m_bark.
*    WRITE : / name ,'is barking'.
  ENDMETHOD.
ENDCLASS.

CLASS lcl_pets IMPLEMENTATION.
  METHOD constructor.
    super->constructorname1 name ).
    pet_name name.
  ENDMETHOD.
  METHOD m_eat.
    super->m_eat).
*    WRITE : / name ,'is eating'.
  ENDMETHOD.
ENDCLASS.

Comments

Popular posts from this blog

SAP ABAP : OOPS Concept - Classes And Objects

SAP ABAP : OOPS Concept - Inheritance

SAP ABAP : OOPS Concept - Encapsulation