Friday, December 18, 2015

OO ABAP: Casting

Use of Casting

Customer specific changes can be easily implemented using casting. Suppose there are two customers, customer1 and customer2. They have some common properties and some individual customer specific properties. So we can maintain their common properties in class general(parent) and individual properties in class customer1(child) and customer2(child). Casting help as us to access these child properties using parent. ie, we don't need to make changes in our programs whenever the individuals customer properties changes. 


Narrow Casting

The assignment of subclass instance to super class instance is narrow casting, because we are switching from 'more detailed view' to 'less detailed view'.

super class = sub class

Widen Casting

The assignment of super class instance to subclass instance is widen casting, because we are switching from 'less detailed view' to 'more detailed view'.

sub class ?= super class


Up Casting and Down Casting

These terms are little confusing. It depends on the view perspective from where we are seeing the inheritance tree. Please see the diagrammatic explanation below.
Later version of SAP follows DOWN-TOP tree structure (Diagram 1).

Down Casting (Narrow Casting)


1. Create a class (Super/Root) with common_method


2. Create a sub class for customer 1 by inheriting super class


3. Redefine COMMON_METHOD in sub class and also create a new method 'METHOD_CUSTOMER1'


4. Call sub class methods using super class object


REPORT  zdil_blog_downcasting.

DATA: lo_general   TYPE REF TO zdil_blog_class_genral,
      lo_customer1 TYPE REF TO zdil_blog_class_customer1.

START-OF-SELECTION.

  CREATE OBJECT lo_general.
  CREATE OBJECT lo_customer1.

* Down Casting

  lo_general = lo_customer1.

  CALL METHOD lo_general->common_method( ).


5. Output


Though we called 'COMMON_METHOD' of super class, system called redefined 'COMMON_METHOD' of sub class due to Down Casting effect.

Up Casting (Widen Casting)


To access the newly created methods of sub class, we can use Up Casting. We have do Down Casting before Up Casting, otherwise it gives dump. 

Sample code


REPORT  zdil_blog_upcasting.
DATA: lo_general   TYPE REF TO zdil_blog_class_genral,
      lo_customer1 TYPE REF TO zdil_blog_class_customer1,
      lo_customer1_temp TYPE REF TO zdil_blog_class_customer1.

START-OF-SELECTION.

CREATE OBJECT lo_customer1_temp.

* Down Casting
  lo_general = lo_customer1_temp.

* Up Casting
  lo_customer1 ?= lo_general.

  CALL METHOD lo_customer1->method_customer1( ).

Output









2 comments: