Type casting concept is related to inheritance. There are 2 types of casting
- Narrow Casting/Up Cast
- 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.
- 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.
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.
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:
Tags
ABAP OOPS