Casting vs. Widening

I'm continuing the discussion from a deleted thread of whether or not statements such as the following...A a = new A();...constitute "implicit casting" or "assignment conversion". I'm in the latter camp, by virtue of the JLS, Chapter 5. Others have disagreed; at least I think they've disagreed.
Thoughts?

I don't consider that there's any cast going on there.
There are several notions of casting one could use:
1) A language level cast, as defined in the JLS. That is quite obviously not present, since, as you pointed out, that kind of cast explicitly uses the cast operator.
2) A cast--in any sense--inserted into the final bytecode by the compiler. As your javap output in the other thread showed, this is also clearly not happening.
3) A cast in a more general sense, corresponding to the compiler explicitly turning a B reference into an A reference internally at some intermediate step that's not manifested in the bytecode. This might be happening in some cases, I suppose. You'd have to look at compiler source code to know for sure. However, I think it would be trivial to show via reflection conterexample that it is not necessary to do this in the upcast sense that another poster was going on about in the thread that was, thank goodness, deleted.
4) A general, cenceptual cast like #3, but without the compiler explicitly doing something. Just a view that "well, since this is an A reference, it must by definition be sort of kind of conceptually casting to A."
Number 4 is pointless to argue, IMHO. It's like talking about how you can picture passing references by value as passing objects by reference. Sure, you can conceptualize it that way if it helps you to follow what's going on, but it has nothing to do with the JSL or any actual compiler or VM mechanism.
Number 3 is pointless unless somebody really cares about what the compiler might do in some situations. Since we can show at least one case where it can't possibly do it, then it's not required that it do it, and I believe the original claim was that it was required to do it.
So 1 and 2 don't occur, 3 is possible but not required, and 4 is irrelevant.
Therefore, with regard to the claim that an upcast is necessary, I say, no, it's not.

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 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>

  • 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

  • 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 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

  • Hi i just to want to know when we use object casting..

    sorry about this newbie question i ve already asked to my tutor but
    didn't get it...
    i just wonder what will happen if we cast object..
    i just can't imagin..coz im just bit slow on creative thinking...
    my currently writing code is like this..
    Integer nextCustID = new Integer("123456");
    Customer customer = new Customer(nextCustID, "Fred");
    customers.put("First", customer);
    customer = (Customer) customers.get("First");
    System.out.println(customer);i don't know about object casting...............................

    You don't cast objects. You just cast references - widening or narrowing their "scope" along the inheritance hierarchy.
    String s = new String("Hello");
    Object o = (Object) s; // Explicit cast not necessary, just for clarification
    String s = (String) o;While "hello" might appear as a String, then as an Object, then again as a String, it is always a String. Only the reference type to it changes.

  • Hi, in oop concepts

    what is th difference between narrow casting and widening casting .

    Hi,
    NARROW CASTING as the name suggests mean when you <b>SEE FEW ATTRIBUTES AND METHODS OF A CLASS THAN THE CLASS actually exposes.</b> That is when you assign a CLASS OBJECT TO a reference of the INTERFACE then using this reference you can only call methods of the interface but not the methods directly under the class.
    <b>
    Meaning the the things that you access using the interface are NARROWED down from the actual class's capability.</b>
    In WIDENING CASTING the reverse happens, that is when you accept a variable which is a reference variable of type say INTERFACE and then assign this reference to a reference variable of type CLASS using <b>?= operator</b> <b>then you can see more things than what you can see using the interface reference</b>, so your acccess to things is<b> WIDENED</b> in this case.
    Regards,
    Sesh<b></b>

  • Type problems

    After typing a line ( with the cursor on the wrong end) the period ends up at the other end. WTF, NEVER SEEN THIS BEFORE. Is there something I could have reset unknowingly that is causing this?

    What kind of TYPE are these parameters? Just to understand better your problem.
    You have two types of Cast, narrowing cast and widening cast
    <b>Narrowing Cast:</b> there is a switch from a view of several components (or generic type) to a view of a few components (upcast)
    <b>Widening Cast:</b> switch from a view of a few components to a view of more components (downcast) and you have to use the operator "?=".
    This is very usefull to cast assignment of Data Reference and Subclass x Superclass.
    Ex:
    DATA: int          TYPE i  VALUE 15,
              Ref_int    TYPE REF TO i,
              Ref_gen  TYPE REF TO data. <i>“generic type</i>
    GET REFERENCE OF int INTO ref_int.
    <i>* narrowing cast:</i>
    ref_gen = ref_int.
    <i>* widening cast:</i>
    Ref_int ?= ref_gen.
    I hope this example help you with cast, anyway you always can use Interface or Inheritance

  • 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

  • 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.

  • 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.

  • 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...

  • 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

Maybe you are looking for

  • Data loading from DSO to Cube

    Hi, I have a question, In book TBW10 i read about the data load from DSO to InfoCube " We feed the change log data to the InfoCube, 10, -10, and 30 add to the correct 30 value" My question is cube already have 10 value, if we are sending 10, -10 and

  • Keynote 6.0.1 Crashing When Entering Text Boxes

    On my late 2012 Mac Mini with 16GB - running Mavericks (up to date) - and Keynote 6.0.1 I am going NUTS! Entering text in a TEXT BOX on a page with an inserted photograph or image is impossible. Every single time, while entering or editing the text b

  • Issue when trying to upgrade FB 4.7 to AIRDSK 3.6

    Hi, I'm desperately trying to upgrade FB 4.7 to AIRSDK 3.6 since 3 weeks. I've followed the various solutions found on forums and the various processes displayed by the "helpx.adobe.com" pages, but none of them works. So please, if a member of Adobe

  • Using Numbers as a timeline program?

    I am writing stories as a hobby and have so many characters and events now with my 3th book that I start to forget what happened when and who was born at what date. I looked for a timeline program on the web but could not find anything that is specia

  • Human Workflow Notification email format

    Hello, I've configured email notification in Human Workflow and able to receive email in plain text format in one line. How do i get email message with html format with text in seperate lines. I even added &#x0D; and xpath command for new line inside