Application Development Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 

widening cast

SagarSontakke
Active Participant
0 Kudos

Dear All,

I am facing one problem in widening cast.

can somebody explain widening cast with example.

i have written one sample code which is giving run time error .

when i am trying to pass the subclass ref to superclass,

its giving runtime error

Thanks

Sagar

report zsvs_class no standard page heading.

----


  • CLASS tset DEFINITION

----


*

----


class test definition.

public section.

methods: display_name.

endclass. "tset DEFINITION

----


  • CLASS test IMPLEMENTATION

----


*

----


class test implementation.

method display_name.

write 😕 'Test'.

endmethod. "display_name

endclass. "test IMPLEMENTATION

----


  • CLASS test_1 DEFINITION

----


*

----


class test_1 definition inheriting from test.

public section.

methods: display_name redefinition.

methods: display_test.

endclass. "tset DEFINITION

----


  • CLASS test_1 IMPLEMENTATION

----


*

----


class test_1 implementation.

method display_test.

write 😕 'Test_1'.

endmethod. "display_test

method display_name.

  • super->display_name( ).

write : / 'redefined'.

endmethod. "display_name

endclass. "test IMPLEMENTATION

start-of-selection.

data : w_test type ref to test.

data : z_test type ref to test_1.

data : itab type table of ref to test.

data : r_test type ref to test.

create object w_test .

z_test ?= w_test.

1 REPLY 1

Former Member
0 Kudos

Widening cast or down casting is refered as such because it changes a reference from a generalized view to a more detailed view.

The first thing you can do to your code is put the casting code in a TRY... CATCH... ENDTRY block. Something like,

TRY.

z_test ?= w_test.

CATCH cx_sy_move_cast_error.

  • Do the error handling

ENDTRY.

If there is still a runtime error, check at what point is it being generated and let me know what the error is. Remember that you cannot call a function or attribute of a child class (test_1) with a with z_test after the widening cast operation cause it is still carrying a reference to the parent class (test). If you do this it WILL generate a runtime error.

When i say functions of the child class, i mean functions that dont exist in the parent class and have been introduced in the child class only.