Narrow Casting and Wide Casting In ABAP OOPS

 Type casting concept is related to inheritance. There are 2 types of casting

  1. Narrow Casting/Up Cast
  2. Widening Casting/Down Cast

Narrow Casting/Up Cast:

  • In Narrow Casting, the subclass instance is assigned to instance of super class.
  • As, we are moving from more specific view to less specific view it is known as Narrow Casting.
  • As, the path goes upwards from subclass to super class it is also known as Up Casting.

lr_parent = lr_child.

Example:

Consider two classes lcl_parent and lcl_child inherited from lcl_parent.

DATA: lr_parent TYPE REF TO lcl_parent.
DATA: lr_child  TYPE REF TO lcl_child.

CREATE OBJECT lr_child.
lr_parent = lr_child.

Widening Casting/Down Cast:

  • In Widening Casting, the superclass instance is assigned to instance of sub class. 
  • As, we are moving from less specific view to more specific view it is known as Widening Casting. 
  • As, the path goes downwards from superclass to subclass it is also known as Down Casting.

lr_child ?= lr_parent.




Example:


DATA: lr_parent TYPE REF TO lcl_parent.
DATA: lr_child    TYPE REF TO lcl_child.

CREATE OBJECT lr_parent.

TRY.
 lr_child ?= lr_parent.
CATCH cx_sy_move_cast_error.
 WRITE:/ 'Widening Cast Failed'.
ENDTRY.

Instead of assigning operator ( = ), casting operator ( ?= ) is used in Widening Cast. 

It is always suggested to catch the exception CX_SY_MOVE_CAST_ERROR while doing widening cast.

Read below article for more information on Narrow Cast and Wide Cast:

Post a Comment

Previous Post Next Post