What is the difference between Upcasting and Downcasting in SAP ABAP?

Data lr_top_floor TYPE REF TO zcl_top_floor

Data lr_ground_floor TYPE REF TO zcl_ground_floor

lr_top_floor = New zcl_top_floor ().

lr_ground_floor = New zcl_ground_floor ().

Downcast:

When you stand in the top floor, the view of the properties such as roads, other houses are visible easily. The view is widened in the top floor. So, we can call it as widening cast When you are in the ground floor, the view is narrowing. The properties are not visible in the ground floor. Therefore it is called as Narrowing cast.

Let us assign the instance of the top floor to the ground floor. When you are able to view the other houses, people will always question your increased visibility. Therefore during the assignment, place a question mark before the ‘=’ sign.

lr_ground_floor ?= lr_top_floor.

Please remember the word Assignment to distinguish the upcast and downcast. In the above case, it is assigned to the ground floor (Downcasting) In other words it is moving down from top floor to ground floor. In this case remember the direction of movement.

So lr_ground_floor ?= lr_top_floor (more view) widening cast.

It is assigned to the ground floor(Downcast).

Upcast:

When you stand on the ground floor, the view is less. You will not be able to see the other properties. People will not question you, as the visibility will be less. Therefore there is no question mark during the assignment of the ground floor instance to the top floor instance.

lr_top_floor = lr_ground_floor (less view) Therefore, narrowing cast.

(Direction,Assignment)

It is assigned to the top floor reference variable. The direction is from ground to top, hence it is named as upcast.