When we assign the instance of the Superclass to the Subclass, than it is called the Widening Cast, because we are moving to the "More Specific View" from the "Less specific view". Due to this reason it is also called the "Down Casting".
Everytime it is not possible to move the Superclass reference to the Subclass, because subclass will(or might) have always more functionality compare to the Superclass. So, we need to be more careful when we use the down casting.
We will use the same ANIMAL Superclass and LION subclass as per the blog post - ABAP Objects: Narrowing Cast
When this Widening Cast is used?
Widening cast can be used when we need to access the Specific functionality of the subclass from the Superclass.
In ABAP, it is necessary to catch the exception CX_SY_MOVE_CAST_ERROR while doing the widening cast to avoid the short-dump.
Code Snippet for Widening Cast (Downcasting) |
*----------------------------------------------------------------------* * This code shows how to use the Widening cast (downcasting) *----------------------------------------------------------------------* START-OF-SELECTION. DATA: lo_animal TYPE REF TO lcl_animal, lo_lion TYPE REF TO lcl_lion, lo_cast_error TYPE REF TO cx_sy_move_cast_error. * * First We have to do Narrow casting in order to set the * Animal reference to LION reference. DATA: lo_tmp_lion TYPE REF TO lcl_lion. CREATE OBJECT lo_tmp_lion. lo_animal = lo_tmp_lion. * * Now, we will do the Widening cast to move the reference from the * Animal to LION (more specific class). TRY. lo_lion ?= lo_animal. CATCH cx_sy_move_cast_error INTO lo_cast_error. WRITE: / 'Widening cast failed 1'. ENDTRY. IF lo_lion IS NOT INITIAL. CALL METHOD lo_lion->hungry( ). CALL METHOD lo_lion->fasting( ). ENDIF. * * Now, we will try to do the widening cast without setting up * the proper object reference in the Super reference. CLEAR: lo_animal, lo_lion, lo_cast_error. CREATE OBJECT lo_animal. TRY. lo_lion ?= lo_animal. CATCH cx_sy_move_cast_error INTO lo_cast_error. WRITE: / 'Widening cast failed 2'. ENDTRY. IF lo_lion IS NOT INITIAL. CALL METHOD lo_lion->hungry( ). CALL METHOD lo_lion->fasting( ). ENDIF.
|
Output of this code snippet is:
0 comments
Post a Comment