Skip to Content
0
Former Member
Jun 10, 2013 at 08:27 AM

Narrow & Widening cast

98 Views

Hello, I'm trying to understand narrow & widening cast, for this reason I develop a simple class in order to understand correctly. Here is my source code:

REPORT ZBC_OBJECTS.

CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS: constructor IMPORTING
im_max_speed TYPE i
im_number_of_wheels TYPE i.
PRIVATE SECTION.

DATA: max_speed TYPE i,
number_of_wheels TYPE i.

ENDCLASS.

CLASS lcl_vehicle IMPLEMENTATION.

METHOD constructor.
max_speed = im_max_speed.
number_of_wheels = im_number_of_wheels.
ENDMETHOD.

ENDCLASS.

CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle.
PUBLIC SECTION.
METHODS: constructor IMPORTING
im_max_speed TYPE i
im_number_of_wheels TYPE i
im_load_capacity TYPE i.
PRIVATE SECTION.
DATA: load_capacity TYPE i.
ENDCLASS.

CLASS lcl_truck IMPLEMENTATION.
METHOD constructor.
super->constructor(
im_max_speed = im_max_speed
im_number_of_wheels = im_number_of_wheels ).
load_capacity = im_load_capacity.
ENDMETHOD.
ENDCLASS.


DATA: vehicle TYPE REF TO lcl_vehicle,
truck TYPE REF TO lcl_truck.

START-OF-SELECTION.

CREATE OBJECT vehicle EXPORTING
im_max_speed = 325
im_number_of_wheels = 4.

CREATE OBJECT truck EXPORTING
im_max_speed = 100
im_number_of_wheels = 8
im_load_capacity = 5000.


vehicle ?= truck. " Vehicle now have attribute +load_capacity (Widening cast)

the widening cast is working (I think), how can I "simulate" the narrowing cast in my own example. Thanks!