‎2007 Jan 24 9:00 AM
‎2007 Jan 24 11:31 AM
Hi ,
Please check out the program .
REPORT ZDIN_CLASS1 .
TYPE-POOLS abap.
Interfaces and classes
INTERFACE if_add.
METHODS add IMPORTING summand TYPE i.
ENDINTERFACE.
INTERFACE if_subtract.
METHODS subtract IMPORTING subtrahend TYPE i.
ENDINTERFACE.
INTERFACE if_add_subtract.
INTERFACES: if_add, if_subtract.
ENDINTERFACE.
CLASS cl_stack DEFINITION.
PUBLIC SECTION.
INTERFACES if_add_subtract.
ALIASES: add FOR if_add~add,
subtract FOR if_subtract~subtract.
DATA amount TYPE i VALUE '100' READ-ONLY.
ENDCLASS.
CLASS cl_stack IMPLEMENTATION.
METHOD if_add~add.
amount = amount + summand.
ENDMETHOD.
METHOD if_subtract~subtract.
amount = amount - subtrahend.
ENDMETHOD.
ENDCLASS.
Global data
DATA: iref1 TYPE REF TO if_add,
iref2 TYPE REF TO if_subtract,
oref TYPE REF TO object.
DATA: ptab TYPE abap_parmbind_tab,
ptab_line LIKE LINE OF ptab,
para TYPE i.
FIELD-SYMBOLS <amount> TYPE i.
Main program
START-OF-SELECTION.
Object instantiation
CREATE OBJECT iref1 TYPE cl_stack.
Method call (short form)
iref1->add( '10' ).
Widening cast
TRY.
iref2 ?= iref1.
iref2->subtract( '20' ).
CATCH cx_sy_move_cast_error.
MESSAGE 'Casting error' TYPE 'I'.
ENDTRY.
Narrowing Cast
oref = iref2.
Dynamic Access
ASSIGN oref->('AMOUNT') TO <amount>.
IF sy-subrc = 0.
BREAK-POINT. "Value of <amount> is 90.
ENDIF.
Dynamic Invoke
TRY.
GET REFERENCE OF para INTO ptab_line-value.
ptab_line-name = 'SUMMAND'.
para = 30.
INSERT ptab_line INTO TABLE ptab.
CALL METHOD oref->('ADD') PARAMETER-TABLE ptab.
BREAK-POINT. "Value of <amount> is 120.
CLEAR ptab.
ptab_line-name = 'SUBTRAHEND'.
para = 40.
INSERT ptab_line INTO TABLE ptab.
CALL METHOD oref->('SUBTRACT') PARAMETER-TABLE ptab.
BREAK-POINT. "Value of <amount> is 80.
CATCH cx_sy_dyn_call_error.
MESSAGE 'Dynamic invoke error' TYPE 'I'.
You will understand what's the use .
Please reward if useful.
‎2007 Jan 25 7:41 AM
Hello Govindu,
Upcasting or Narrowing Cast can be used to prepare for generic access. A user who is not interested in the finer/specific points of the subclass instances but simply wants to access the shared/inherited components, can use a superclass reference (with narrowing cast) for this.
With widening cast/downcating there is no restriction that only inherited components of subclass can be accessed. When specific components of subclass instances need to be addressed, widening cast can be used.
Award points if found useful.
Regards
Indrajit