Narrowing cast and widening cast

Hi All,
       I want to know what is the use of a narrowing cast and a widening cast in ABAP objects.
Can someone please give an example ?
Regards,
Ashish

Hi,
Check out this link, This will guide you on ABAP Objects
http://www.sap-press.de/katalog/buecher/htmlleseproben/gp/htmlprobID-28?GalileoSession=22448306A3l7UG82GU8#level3~3
Both narrow and wide casting are related to inheritance.
In Narrow casting, you assign a runtime object of subclass to runtime object of superclass. By this assignment , you can access your subclass by using runtime object of your superclass. But here the important point is that, you are assigning subclass reference to super class reference, so you can only access the inherited components of subclass through super class reference.
Suppose you have a super class lcl_vehicle. it has two subclasses lcl_car and lcl_truck.
r_vehicle = r_car.
In Wide casting, you assign a superclass reference to subclass reference . Before this, you do narrow casting,
Now when you assign a superclass reference to subclass reference. You can access the inherited as well as the specific components of subclass.
taking the same example,
r_car ?= r_vehicle.
'?='  wide cast operator.
Regards
Abhijeet

Similar Messages

  • Narrow Cast and Widening cast in OOPs

    hi friends,
    Can u please clear with the above two concepts ..... i have many doubts on this ...
    first of all Y we need the concept of Narrow cast and widenning cast ?
    Expecting your answers ...
    Thanks in advance
    Cheers
    Kripa Rangachari .....

    hi Kripa,
    “Narrowing” cast means that the assignment changes from a more specialized view (with visibility to more components) to a more generalized view (with visibility to fewer components).
    “Narrowing cast” is also referred to as “up cast” . “Up cast” means that the static type of the target variable can only change to higher nodes from the static type of the source variable in the inheritance tree, but not vice versa.
    <b>Reference variable of a class assigned to reference variable of class : object</b>
    class c1 definition.
    endclass.
    class c1 implementation.
    endclass.
    class c2 definition inheriting from c1.
    endclass.
    class c2 implementation.
    endclass.
    start-of-selection.
    data : oref1 type ref to c1,
            oref2 tyep ref to c2.
    oref1 = oref2.
    <b>Widening Cast</b>
    DATA:     o_ref1 TYPE REF TO object,                o_ref2 TYPE REF TO class.
    o_ref2 ?= o_ref1.
    CATH SYSTEM-EXCEPTIONS move_cast_error = 4.
         o_ref2 ?= o_ref1.
    ENDCATCH.
    In some cases, you may wish to make an assignment in which the static type of the target variable is less general than the static type of the source variable. This is known as a widening cast.
    The result of the assignment must still adhere to the rule that the static type of the target variable must be the same or more general than the dynamic type of the source variable.
    However, this can only be checked during runtime. To avoid the check on static type, use the special casting operator “?=“ and catch the potential runtime error move_cast_error
    Regards,
    Richa

  • What is upcast/ narrowing cast and widening cast/downcast?

    Hi All SAPIENT,
    What is upcast/ narrowing cast and widening cast/downcast?Why we are using upcast and downcast?Please send me good reply to my mail id pankaj.sinhas2gmail.com.
    Regards
    Pankaj Sinha.

    Hi Srinivasulu,
    Narrowing cast means whenever Sub-Class Reference is Assigned to a Super Class reference it is Narrowing Cast,
    Widening cast means Super Class reference  is Assigned to a Sub-Class Reference then it is Widening Cast.
    See the following links for more information,
    [http://help-abap.blogspot.com/2008/09/abap-objects-narrowing-cast-upcasting.html]
    [http://help-abap.blogspot.com/2008/09/abap-objects-widening-cast-down-casting.html]
    Regards,
    Raghava Channooru.

  • Narrow cast and wide cast in ABAP OO

    Hi Xperts
    Considering the code below can the concepts of narrowing cast and widening cast be explained ? Kindly help me in getting a clear picture of the usage of it.
    CLASS C1 DEFINITION.
      PUBLIC SECTION.
        CLASS-DATA: COUNT TYPE I.
        CLASS-METHODS: DISP.
    ENDCLASS.                    "defintion  C1
    CLASS C1 IMPLEMENTATION.
      METHOD DISP.
        WRITE :/ COUNT.
      ENDMETHOD.                    "disp
    ENDCLASS.                    "c1 IMPLEMENTATION
    CLASS C2 DEFINITION INHERITING FROM C1.
      PUBLIC SECTION.
        CLASS-METHODS: GET_PROP.
    ENDCLASS.                    "c2  INHERITING C1
    CLASS C2 IMPLEMENTATION.
      METHOD GET_PROP.
        COUNT = 9.
        CALL METHOD DISP.
      ENDMETHOD.                    "get_prop
    ENDCLASS.                    "c2 IMPLEMENTATION
    START-OF-SELECTION.
      DATA: C1_REF TYPE REF TO C1,
            C2_REF TYPE REF TO C2.
    PS: Pls dont post any links as i already gone thru couple of those in SDN but couldnt get a clear info

    Hi
    I got to know abt narrow cast: referecing a super class ref to a subclass ref so that the methods in subclass can be accessed by the super class reference. Below is snippet of the code i'd checked. Hope this is correct to my understanding. If any faults pls correct me. Also if anyone can explain wideing cast in this context will be very helpful
    FOR NARROW CAST
    {size:8}
    CLASS C1 DEFINITION.
      PUBLIC SECTION.
        CLASS-DATA: COUNT TYPE I.
        CLASS-METHODS: DISP_COUNT.
    ENDCLASS.                    "defintion  C1
    CLASS C1 IMPLEMENTATION.
      METHOD DISP_COUNT.
        WRITE :/ 'Class C1', COUNT.
      ENDMETHOD.                    "disp
    ENDCLASS.                    "c1 IMPLEMENTATION
    CLASS C2 DEFINITION INHERITING FROM C1.
      PUBLIC SECTION.
        CLASS-METHODS: GET_PROP,
                       DISP.
    ENDCLASS.                    "c2  INHERITING C1
    CLASS C2 IMPLEMENTATION.
      METHOD GET_PROP.
        COUNT = 9.
        CALL METHOD DISP.
      ENDMETHOD.                    "get_prop
      METHOD DISP.
        WRITE :/ 'Class C2', COUNT.
      ENDMETHOD.                    "DISP
    ENDCLASS.                    "c2 IMPLEMENTATION
    START-OF-SELECTION.
      DATA: C1_REF TYPE REF TO C1,
            C2_REF TYPE REF TO C2.
      CREATE OBJECT: C2_REF TYPE C2.
    *  CREATE OBJECT: C1_REF TYPE C1.
      BREAK-POINT.
      C1_REF = C2_REF.
      CALL METHOD C1_REF->DISP_COUNT.
      CALL METHOD C1_REF->('GET_PROP').
    {size}
    Edited by: Prabhu  S on Mar 17, 2008 3:25 PM

  • Change Narrowing and Widening Cast

    I have ABAP Object 2007 book from Horst Keller and I also have a 7.0 SAP System.
    SAP have changed the terminology from SAP 6.40.
    Please see this hyperlink  [Version 7.0 ABAP Modification 6|http://help.sap.com/abapdocu/en/ABENNEWS-70-DOCU.htm#!ABAP_MODIFICATION_6@6@]
    In addition when I click on Help on MOVE and the Casting operator in my 7.0 Version system is explained as
    Up Cast
    Also referred to as widening cast. Assignment between reference variables, where the static type of the target variables is similar or identical to the static type of the source variables.
    Down cast
    Also called a narrowing cast, a down cast is an assignment between reference variables in which the typr static type of the target variable more specific than the static type of the source variable. A down cast is only possible in assignments with the casting operator (?=) or MOVE ... ?TO. Compare with up cast
    SAP now want you to use the unambiguous terms of UP and DOWN  Version 7.0 of course.
    Does anybody have a pre640 SAP system (46C,47) that can confirm that the terminology has changed ?

    Hi,
    The terminology has not changed, but its a prior mistake made while writing notes, but the concept still remains the same as far as I have check in systems...
    Regards,
    Siddarth

  • Narrow Casting Vs Widening Casting

    Hello,
    Can anybody please explain me the difference with an example between <b><i>Narrow Casting</i></b> and <i><b>Widening</b></i> <i><b>Casting</b></i> in ABAP Objects.
    Regards
    Kalyan

    Hi Kalyan
    In fact, the names imply everything. Let me illustrate a bit. This illustration will deal with one aspect which I think will be enough at least to understand the concept simply. Think of two instances (objects) of two classes one of which is inherited from the other, that is; one is a general class and the other is a specialized class of it.
    <u>e.g.</u>
    Class 1 --> land_vehicle
    Class 2 --> truck
    The class <b>land_vehicle</b> has following attributes:
      max_speed
      number_of_wheels
      number_plate
    The class <b>truck</b> has following attributes:
      max_speed [inherited]
      number_of_wheels [inherited]
      number_plate [inherited]
      <i>load_capacity</i> [special to truck class]
    Now, assume you have instantiated these classes as
    <b>"land_vehicle_obj"</b> and <b>"truck_obj"</b> respectively from these classes.
    Between these two objects, you can assign one to the other and at this point casting occurs.
    i. If you assign <i>truck_obj</i> to <i>land_vehicle_obj</i> you lose the special attribute <i>load_capacity</i> since you go from the specialized on to the general one. Thus, this is a <b>narrowing cast</b>.
    i. If you assign <i>land_vehicle_obj</i> and <i>truck_obj</i> you do not lose any attribute, nevertheless you add a new one. Thus this is a <b>widening cast</b>.
    Regards
    *--Serdar <a href="https://www.sdn.sap.com:443http://www.sdn.sap.comhttp://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.sdn.businesscard.sdnbusinesscard?u=qbk%2bsag%2bjiw%3d">[ BC ]</a>

  • Share small real-time example using Narrowing Cast & Widening Cast

    Hi Guys,
    I am trying to understand the concept of Narrowing Cast and Widening Cast and getting confused why we are using these Casts. When we can always access the method of Subclass using its ref object in Narrowing ) and use the Super class with its ref object (in Widening).
    I understand the concept but could not understand under what situation cast is preferred.There are articles all over the web to explain the concept, but non told us why and when we are forced to us these CASTS.
    I will appreciate if somebody can share a small real-time example where use of Narrowing and Widening Cast is advisable.
    Thanks,

    It looks like this topic has lost steam. 
    I'm surprised this isn't a more intense conversation. There are many applications that need to share data.
    In my application I have many hundreds (in some few cases in the thousands) of different types of data streams including DIO, Analog, and many different types of Serial buses.
    My application is already controlling the hardware and data streams, but others want to peak into my I/O including what is happening on the serial buses.
    To create a 'get' function for each I/O in a web page would seem farily intense (although I could probably create a VI script to help build it).
    I was looking for solutions along the lines of maybe coping the data into a VISA service (if that is possible), or publishing to a datasocket server, or creating a network published variable.
    I need to be considerate of the possibility of hundreds of serial buses banging a service and the possible bandwidth impacts. So I'm searching for a solution that is both easy to implement and low on resources.
    For now I'm leaning towards datasockets. Does anybody have an opinions on this?

  • Narrow casting vs wide casting

    Hello All,
    I have small requriemn..
    I have a super class A and a sub class B.
    In both the classes I have a method XYZ.
    So, A has the following methods
    ABC
    XYZ
    B has the following methods
    XYZ
    Now I have want to access the sub class methods from super class...i.e., in my example...Method XYZ of B class needs to be accessed from method ABC or XYZ or A.
    How do I do?
    And more over..what is the difference between Narrow Casting and Wide casting?
    Kalyan

    Hi Priya,
    Consider the below Example for accessing the subclass method from Superclass:
    CLASS LCL_SUPERCLASS DEFINITION.
       PUBLIC SECTION.
           METHODS: ABC, XYZ.
    ENDCLASS.
    CLASS LCL_SUPERCLASS IMPLEMENTATION.
      METHOD ABC.
       CALL METHOD ME->XYZ.
      ENDMETHOD.
      METHOD XYZ.
      ENDMETHOD.
    ENDCLASS.
    CLASS LCL_SUBCLASS DEFINITION
           INHERITING FROM LCL_SUPERCLASS.
       PUBLIC SECTION.
          METHODS XYZ REDEFINITION.
    ENDCLASS.
    CLASS LCL_SUBCLASS IMPLEMENTATION.
      METHOD XYZ.
      ENDMETHOD.
    ENDCLASS.
    START-OF-SELECTION.
    DATA: O_SUPER TYPE REF TO LCL_SUPERCLASS,
               O_SUB     TYPE REF TO LCL_SUBCLASS.
    CREATE OBJECT: O_SUPER, O_SUB.
    CALL METHOD O_SUPER->ABC.
    CALL METHOD O_SUB->ABC.
    In the above example, When you call the superclass method ABC using CALL METHOD O_SUPER->ABC, as you see in the implementation part of the Method it will inturn call the Superclass method XYZ.
    Here ME will point to the instance of the Superclass.
    But the CALL METHOD O_SUB->ABC will call the method ABC ( this is inherited from Superclass to Subclass )and inturn it calls the method XYZ of the SUbclass since ME now points to the object O_SUB of the Subclass.
    Hope this is clear.
    Regards,
    Nirupamaa.

  • Diff Between widening Cast & Narrowing Casting

    Hi,
    What are differences between widening Cast & Narrowing Casting ?
    Give some exaples also.
    Thanks

    Hey fren,
    Narrowing Cast is also known as Upcasting...
    Widening Cast is known as Downcasting...
    Let us take an example...
    We define a class lcl_vehicle and other class lcl_truck inherited from lcl_vehicle.
    CLASS lcl_vehicle DEFINITION.
          PUBLIC SECTION.
             METHODS constructor
                       IMPORTING im_make_v  TYPE string.
             METHODS estimate_fuel
                       IMPORTING im_distance   TYPE s_distance
                       RETURNING value(re_fuel) TYPE s_capacity
             METHODS get_make........
             METHODS get_count........
              METHODS display_attributes........
          PROTECTED SECTION.
              DATA r_tank TYPE REF TO lcl_tank.
          PRIVATE SECTION.
              DATA make TYPE string.
    ENDCLASS.
    CLASS lcl_vehicle IMPLEMENTATION.
              METHOD constructor.
                   make = im_make_v.
              ENDMETHOD.
              METHOD get_make.
              ENDMETHOD.
              METHOD get_count.
              ENDMETHOD.
              METHOD display_attributes.
              ENDMETHOD.
    ENDCLASS.
    Now we define a sub class lcl_truck to super class lcl_vehicle.
    CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle.
           PUBLIC SECTION.
                METHODS constructor IMPORTING im_make_t TYPE string
                                                             im_cargo_t TYPE s_plan_car
                METHODS estimate_fuel REDEFINITION.
                METHODS get_cargo RETURNING value( re_cargo ) TYPE s_plan_car.
           PRIVATE SECTION.
              DATA max_cargo TYPE s_plan_car.
    ENDCLASS.
    CLASS lcl_truck IMPLEMENTATION.
          METHOD constructor.
               CALL METHOD super->constructor( im_make_v  = im_make_t ).
                max_cargo = im_cargo_t.
          ENDMETHOD.
          METHOD estimete_fuel.
              DATA total_weight TYPE w_weight.
              total_weight = max_cargo + weight.
              re_fuel = total_weight * im_distance * correction_factor.
           ENDMETHOD.                   
    ENDCLASS.
    Now we again define one more subclass lcl_bus to superclass lcl_vehicle.
    CLASS lcl_bus DEFINITION INHERITING FROM lcl_vehicle.
    PUBLIC SECTION.
                METHODS constructor IMPORTING im_make_b TYPE string
                                                             im_load_b TYPE s_plan_car
           PRIVATE SECTION.
              DATA max_load TYPE s_plan_car.
    ENDCLASS. 
    CLASS lcl_bus IMPLEMENTATION.
          METHOD constructor.
               CALL METHOD super->constructor( im_make_v  = im_make_b ).
                max_cargo = im_load_b.
          ENDMETHOD.
          METHOD estimete_fuel.
              DATA total_weight TYPE w_weight.
              total_weight = max_passengers * average_weight + weight.
              re_fuel = total_weight * im_distance * correction_factor.
           ENDMETHOD.                   
    ENDCLASS.
    Variables of the type 'reference to superclass' can also refer to subclass instances at runtime.
    This is called as Narrowing Casting...
    Lets see how it works...
    * Creating references to the classes.........
    DATA:
        r_vehicle TYPE REF TO lcl_vehicle,
        r_truck    TYPE REF TO lcl_truck,
        r_bus      TYPE REF TO lcl_bus.
    *Creating an object of class lcl_truck.........
    CREATE OBJECT r_truck.
    *Narrowing Cast ................
    r_vehicle = r_truck.
    Now reference --> superclass.... r_vehicle will point to only the inherited compenents of lcl_truck.
    If you assign a subclass reference to a superclass reference, this ensures that all components that can be accessed syntactically after the cast assignment are actually available in the instance.
    The subclass always contains at least the same components as the superclass. After all, the name and the signature of redefined methods are identical.
    The user can, therefore, address the subclass instance in the same way as the superclass instance. However, he is restricted to using only the inherited components. In this example, after the assignment, the methods GET_MAKE, GET_COUNT, DISPLAY_ATTRIBUTES and ESTIMATE_FUEL of the instance LCL_TRUCK can only be accessed using the reference R_VEHICLE. If there are any restrictions regarding visibility, they are left unchanged.
    It is not possible to access the specific components from the class LCL_TRUCK of the instance (GET_CARGO in the above example) using the reference R_VEHICLE. The view is thus usually narrowed (or at least unchanged). That is why we describe this type of assignment of reference variables as narrowing cast. There is a switch from a view of several components to a view of a few components. The term upcast is also common.
    A typical use for narrowing cast assignments is to prepare for generic access. A user who is not at all interested in the finer points of the instances of the subclasses but who simply wants to address the shared components could use a superclass reference for this access.
    In the example shown here, assume that a travel agency (LCL_RENTAL) needs to manage all imaginable kinds of vehicles in one list. This leads to the question of what types should be assigned to the internal table for the references to airplane instances. You should also assume that the car rental company needs to be able to calculate only the required amount of fuel for all its vehicles.  Correspondingly, the ESTIMATE_FUEL method is defined in the superclass LCL_VEHICLE and is redefined in all subclasses.
    This is about Narrowing Cast.
    Inspire if this was needful,
    Warm Regards,
    Abhi...

  • Usage of widening cast in abap oops

    hi experts,
    I understood the widening cast concept. i want to know in what scenarios, the usage of widening cast makes sense. does the widening improve performance of the program? is there any scenario where we MUST use the widening cast in the logic? i want to understand how do we justify the usage of widening cast.
    please do not give me links explaining widening case. I know what widening cast is, but want to understand the need for it and how it helps in programing.
    thanks

    As for the thread's question: you use it when you have a subclass instance being pointed at by a superclass reference, and you need to access subclass specific components.
    Adding about widening / down cast:
    I repeat: you don't have choice.
    You actually do. Check the following example. BAPIRET2_T is a table type for BAPIRET2.
    You can call the method YOU know the actual referenced object of a subclass supports dynamically, like this:
    * Using downcasting
    DATA lo_tabledescr TYPE REF TO cl_abap_tabledescr.
    DATA lo_structdescr TYPE REF TO cl_abap_structdescr.
    DATA lv_linetypename  TYPE string.
    TRY.
        lo_tabledescr   ?= cl_abap_typedescr=>describe_by_name( 'BAPIRET2_T' ).
        lo_structdescr  ?= lo_tabledescr->get_table_line_type( ).
      CATCH cx_sy_move_cast_error.
        MESSAGE 'Error in downcast!' TYPE 'A'.
    ENDTRY.
    lv_linetypename = lo_structdescr->get_relative_name( ).
    WRITE: /, lv_linetypename.
    * Alternative way using dynamic calling
    DATA lo_typedescr_tab TYPE REF TO cl_abap_typedescr.
    DATA lo_typedescr_str TYPE REF TO cl_abap_typedescr.
    lo_typedescr_tab   = cl_abap_typedescr=>describe_by_name( 'BAPIRET2_T' ).
    TRY.
        CALL METHOD lo_typedescr_tab->('GET_TABLE_LINE_TYPE')
          RECEIVING
            p_descr_ref = lo_typedescr_str.
      CATCH cx_sy_dyn_call_error.
        MESSAGE 'Error in dynamic call!' TYPE 'A'.
    ENDTRY.
    lv_linetypename = lo_typedescr_str->get_relative_name( ).
    WRITE: /, lv_linetypename, '...again'.
    Note that in either approach, you should catch the relevant exception(s) that may occur, unless you are certain about the object's actual subclass.
    Edited by: Alejandro Bindi on Mar 31, 2010 5:47 PM
    As you can see I got confused by the narrowing / widening terms as well. I also found out the terms upcast / downcast to be much easier to understand.

  • Widening casting

    Hi,
    I am a debutant in ABAP OO. I am trying to understand the concept of Widening casting with lots of example found in SDN, but still I can't come to any conclusion on this.
    Well I understood from one of the example that , before doing the widening , we have to do narrow casting..
    DATA: lo_animal TYPE REF TO lcl_animal,   " Super Class
            lo_lion          TYPE REF TO lcl_lion,        " Sub class
            lo_tmp_lion   TYPE REF TO lcl_lion.       " Sub class
      CREATE OBJECT lo_tmp_lion.
      lo_animal = lo_tmp_lion.                  " Narrow Casting
    lo_lion ?= lo_animal.     " Widening
    Here my question is why do we have to assign the instance of lo_animal to lo_lion which is having the same instance of lo_lion( lo_lion & lo_tmp_lion are reference var of same class ). and i also found an another example from  one of the SDN thread for widening which i really can't undersatnd.
    DATA lo_tabledescr TYPE REF TO cl_abap_tabledescr.
    DATA lo_structdescr TYPE REF TO cl_abap_structdescr.
    DATA lv_linetypename  TYPE string.
    TRY.
        lo_tabledescr   ?= cl_abap_typedescr=>describe_by_name( 'BAPIRET2_T' ).
        lo_structdescr  ?= lo_tabledescr->get_table_line_type( ).
      CATCH cx_sy_move_cast_error.
        MESSAGE 'Error in downcast!' TYPE 'A'.
    ENDTRY.
    lv_linetypename = lo_structdescr->get_relative_name( ).
    WRITE: /, lv_linetypename.
    * Alternative way using dynamic calling
    DATA lo_typedescr_tab TYPE REF TO cl_abap_typedescr.
    DATA lo_typedescr_str TYPE REF TO cl_abap_typedescr.
    lo_typedescr_tab   = cl_abap_typedescr=>describe_by_name( 'BAPIRET2_T' ).
    TRY.
        CALL METHOD lo_typedescr_tab->('GET_TABLE_LINE_TYPE')
          RECEIVING
            p_descr_ref = lo_typedescr_str.
      CATCH cx_sy_dyn_call_error.
        MESSAGE 'Error in dynamic call!' TYPE 'A'.
    ENDTRY.
    lv_linetypename = lo_typedescr_str->get_relative_name( ).
    WRITE: /, lv_linetypename, '...again'.
    Please give me some hints to break through this.
    Thanks in advace,
    Eti.

    Hello Eti,
    I think you're aware of Narrowing & Widening Cast, if not Arshad's response explains these concepts.
    ... why do we have to assign the instance of lo_animal to lo_lion which is having the same instance of lo_lion( lo_lion & lo_tmp_lion are reference var of same class ) ...
    To understand this you need to know - [Static Type|http://help.sap.com/abapdocu_731/en/abenstatic_type_glosry.htm] and  [Dynamic Type|http://help.sap.com/abapdocu_731/en/abendynamic_type_glosry.htm] for reference variables. (This applies to both data and object reference variables).
    The golden-rule for assignment of reference variables is,
    Dynamic type of a ref. variable must always be more specific than the static type.
    DATA: lo_animal TYPE REF TO lcl_animal,"Super Class
          lo_lion   TYPE REF TO lcl_lion. "Sub Class
    The static type of the ref. variable lo_lion is lcl_lion. Now let's consider this assignment,
    lo_lion = lo_animal.
    The compiler interprets the dynamic type of lo_lion (after this assignment) would be lcl_animal. It is more generic compared to the static type( lcl_lion ), since lcl_animal is a super-class of lcl_lion, so the compiler will throw a static syntax error. (Remember the "golden-rule" of reference variable assignment)
    The [casting operator|http://help.sap.com/abapdocu_731/en/abencasting_operator_glosry.htm] is just an instruction to the compiler to skip the static syntax check during the widening cast,
    lo_lion ?= lo_animal. "Widening Cast
    Always remember that for Widening Casts the "golden-rule" of assignment will be checked during runtime.
    If the rule is not satisfied, it'll result in an exception - CX_SY_MOVE_CAST_ERROR ! In order to avoid this situation, the demo program uses a temporary reference variable - lo_tmp_lion.
    lo_animal = lo_tmp_lion. "Narrow Casting
    lo_lion ?= lo_animal."Widening cast
    Sorry for this big post, hope it helps & reduces your confusion
    BR,
    Suhas
    PS: Normally when you're doing a Widening Cast you would not be required to use a temporary ref. variable.

  • Widening casting-code

    class parent definition.
      public section.
      data pub_parent type i.
      endclass.
      class child definition inheriting from parent.
        public section.
        data pc type i.
        endclass.
        data parent type ref to parent.
        data child type ref to child.
        data child1 type ref to child.
    create object child.
    create object parent.
        try.
          parent ?= child.
          catch cx_sy_move_cast_error.
            write 'error'.
            endtry.
    Hi all
    code snippet above doesnt gives me any error..I am doing narrow casting here with a widening cast operator ?=.does that mean ,when it comes to narrow casting u can use either = or ?=.it doesnt make any difference?

    I'll try to explain this using an example.
    DATA: go1 TYPE REF TO object,      "More generic
          go2 TYPE REF TO zcl_myclass. "Less generic
    When you try to assign a 'more-generic' ref. to a 'less generic' ref., the static check performed by the compiler throws a compilation error.
    * Assign a more generic ref. to less generic ref.
    go2 = go1.
    The compiler checks the static types of go1 & go2 and since the assignment is not compatible(more generic is being assigned to less generic) syntax error is raised.
    The casting operator '?=' is a kind of instruction to the compiler to skip the static check & perform the checks during runtime!
    CREATE OBJECT go1 TYPE zcl_myclass.
    TRY .
    * Static compiler check is skipped. The compatibility is checked only
    * at runtime
        go2 ?= go1.
        MESSAGE 'Casting is successful' TYPE 'S'.
      CATCH cx_sy_move_cast_error.
        MESSAGE 'Error in casting' TYPE 'E'.
    ENDTRY.
    The compiler checks the type of go1 at runtime & since the assignment is compatible no exception is raised.
    Consider this example, the exception CX_SY_MOVE_CAST_ERROR is raised at runtime since the dynamic types are not compatible!
    DATA: gx_err  TYPE REF TO cx_sy_move_cast_error,
          gv_msg  TYPE string.
    CREATE OBJECT go1 TYPE zcl_airlines.
    TRY .
    * Static compiler check is skipped. The compatibility is checked only
    * at runtime
        go2 ?= go1.
        MESSAGE 'Casting is successful' TYPE 'S'.
      CATCH cx_sy_move_cast_error INTO gx_err.
        gv_msg = gx_err->get_text( ).
        MESSAGE gv_msg TYPE 'S'.
    ENDTRY.
    But i could use the ?=,operator for assigning a less_gen to a more_gen ref.variable.why?
    The casting operator '?=' can be used for both narrowing as well as widening cast. But in case of widening cast, its use is redundant.
    Hope you get my point.
    BR,
    Suhas
    Edited by: Suhas Saha on Jun 13, 2011 5:16 PM

  • Widening cast

    hi,
    I saw sample  application.
    In that application do_init method have following code.
    method do_init .
    Create an instance of the search model
    query ?= me->create_model(
    class_name = 'ZCL_MODEL'
    model_id = 'query' ).
    endmethod.
    Can anyone explain why we are using widening cast?

    Hi,
    Go to ABAPDOCU tcode and see example programs in abap objects section, you will find separate programs for upcasting and downcasting .
    Up-Cast (Widening Cast)
    Variables of the type reference to superclass can also refer to subclass instances at runtime.
    If you assign a subclass reference to a superclass reference, this ensures that
    all components that can be accessed syntactically after the cast assignment are
    actually available in the instance. The subclass always contains at least the same
    components as the superclass. After all, the name and the signature of redefined
    methods are identical.
    The user can therefore address the subclass instance in the same way as the
    superclass instance. However, he/she is restricted to using only the inherited
    components.
    In this example, after the assignment, the methods GET_MAKE, GET_COUNT,
    DISPLAY_ATTRIBUTES, SET_ATTRIBUTES and ESTIMATE_FUEL of the
    instance LCL_TRUCK can only be accessed using the reference R_VEHICLE.
    If there are any restrictions regarding visibility, they are left unchanged. It is not
    possible to access the specific components from the class LCL_TRUCK of the
    instance (GET_CARGO in the above example) using the reference R_VEHICLE.
    The view is thus usually narrowed (or at least unchanged). That is why we
    describe this type of assignment of reference variables as up-cast. There is a
    switch from a view of several components to a view of a few components. As
    the target variable can accept more dynamic types in comparison to the source
    variable, this assignment is also called Widening Cast
    Static and Dynamic Types of References
    A reference variable always has two types at runtime: static and dynamic.
    In the example, LCL_VEHICLE is the static type of the variable R_VEHICLE.
    Depending on the cast assignment, the dynamic type is either LCL_BUS or
    LCL_TRUCK. In the ABAP Debugger, the dynamic type is specified in the form
    of the following object display.
    Reward Points if found helpfull..
    Cheers,
    Chandra Sekhar.

  • Overcome the runtime error from Widening Cast

    Good Afternoon.
    I created a Super class and Sub Class.
    I created an object for super class reference variable.
    Then i pass like this.
    sub ?= super.
    Then call the Super Class emthods by using Sub class reference variable.
    Then press the Execute button.
    Then it goes to the DUMP.
    While i am using Narrowing Cast then it is working Properly.
    But for the Widening Cast only it is taking the problem. It goes to the dump.
    In BSP Widening cast working properly.
    For my program why it is going to dump.
    How i over come that DUMP.
    Is there any Exceptions or give me the reson why it is going it dump. how i will solve that problem.
    Give the data on above problem with screen shorts if possible.
    Thank you.
    B. Krishna.

    Hi Krishna,
    You can down-cast(widening cast) a class ref variable into its sub-class' class ref variable only if you have already done an up-cast(narrowing cast) of sub-class' class ref variable into the super class' class ref variable ....
    that is
    sub ?= super.
    is possible only if
    super = sub.
    was already done...
    If u r getting MOVE_CAST_ERROR error, this could be the reason...
    ~Jose

  • Use of Widening Cast in Inheritence

    Hello All,
    Request you to help me in understanding the use of widening cast in Inheritence.
    As of my understanding, before widening cast we need to copy the a subclass reference z_sub1 to a superclass reference z_super1 (to ensure that contents of superclass reference corresponds to the type requirement of the subclass reference used in widening cast). Then we assign the superclass referenece z_super1 to another subclass reference z_sub2.
    data: z_sub1     type ref to zl_lcl_sub,
            z_super1  type ref to zl_lcl_super,
            z_sub2     type ref to zl_lcl_sub.
    create object z_sub1.
    z_super1  = z_sub1.
    zsub2 ?=  z_super1. " Widening cast
    Now instaed of doing this, if we directly create an instance zsub3 of subclass, will it different from zsub2  obtained in widening cast.
    data zsub3  type ref to zl_lcl_sub.
    create object zsub3.
    Does widening cast provide any additional advantage over this?
    Regards
    Indrajit

    Dear Indrajit,
       The basic aim of casting is to provide assignment between references.By this it means after assignment both the source & target will point to the same object.
       As you said, if we use,
    <b>   data zsub3 type ref to zl_lcl_sub.
       create object zsub3.</b>
       it  will cause a new object to be created of type ZL_LCL_SUB, which will be totally different from ZSUB2. The requirement here is to assign the reference of ZSUB2 to Z_SUPER1 so that both will pointer to the same object. If Widening Cast is not used then Syntax Check error  will occur due to the fact that Z_SUB2 and Z_SUPER1 is not compatible.For normal reference assignment, the target (Z_SUB2) must be a subset of target i.e (Z_SUPER1).Which is not true in this case. Hence Widening Cast is used.
       I hope its clear now....
      Regards,
    Samson.

Maybe you are looking for

  • EBS Installation on XP and WIN2003 Server (11.10.2)

    Oracle Applications Rapid Install Wizard Install log >> Using Rapid Wizard Version : 11.5.10.35 >> Install session started : Mon Oct 03 09:02:52 GMT+08:00 2005 >> Rapid Wizard source location : G:\Stage11i\startCD\Disk1\rapidwiz >> Command Line argum

  • Scroll-bars in FPM

    Hi Gurus, I've configured all containers in GAF configuration and set it No Scroll-bar. However, it did not take any effect on my FPM application - I still see 2 vertical scroll-bars and a horizontal scroll-bar in EP iview. Any ideas? Best regards, J

  • Creating new App - error

    Hello I Recive That error in creating new application using apex 3 (oracle xe) I loged in by user HR (DBA) ORA-20001: Unable to create modules. ORA-20001: create_table error: ORA-20001: Excel load run ddl error: ORA-01031: insufficient privileges

  • Defining one application module for several DBs

    Hi, Is it possible to define one application module that serves two different DBs? In other words: If I need to use two DBs in my application, how many application module should I define? Thanks in advance

  • Error when installing ICQ for Mac

    Today I attempted to install the official ICQ messenger for Mac (which I downloaded here: http://download.icq.com/download/mac/en ) but the installation of the .air file failed and asked me to contact the software creator for a new installation file.