Casting in ABAP Objects
Casting in ABAP Objects
Type of Casting:
1. Narrowing Cast( Upcasting):- When we assign the instance of the Sub class back to the instance
of the Super class, than it is called the "Narrow Casting", because we are switching from
a "More Specific view of an object" to "less specific view".
2. Widening Cast(Downcasting):- When we assign the instance of the Super class to the Subclass,
than it is called the Widening Cast, because we are moving to the "More Specific View"
from the "Less specific view".
ENDMETHOD.
METHOD calc_area.
WRITE :/ 'Area Of Crcle = 2iiR'.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
data : o_cir type REF TO lcl_circle.
create OBJECT o_cir.
call METHOD o_cir->draw( ). " calls subclass Draw() method
call METHOD o_cir->calc_area( ).
uline.
"--------- Narrow cast(Upcast)---------------"
data : o_shp type REF TO lcl_shape.
o_shp = o_cir. " Narrow cast(Upcast)
call METHOD o_shp->draw( ). " calls sub class Draw() method
"call METHOD o_shp->calc_area( ) . " compilation error
uline.
"---------- Widening Cast(Downcast) -----------"
data : o_cir1 type REF TO lcl_circle.
" o_cir1 = o_shp. " complilation erroro_cir1 ?= o_shp. " Widening Cast(Downcast)
call METHOD o_cir1->draw( ). " calls subclass Draw() method
call METHOD o_cir1->calc_area( ).
-------------------------------------------------------Output-------------------------------------------------------------------