Upcasting and narrow casting in oo-abap

hi friends,
please tell me clearly about the Up casting and Down casting with examples in OO-ABAP.
thanks and regards.
Moderator message : Search for available information, read forum rules before posting. Thread locked.
Edited by: Vinod Kumar on Nov 9, 2011 5:32 PM

Hi,
     Instance components exist separately in each instance (object) of the class and are referred using instance component selector using u2018u2019.
     Static components can be used without even creating an instance of the class and are referred to using static component selector     u2018 =>u2019 .
CLASS c1 DEFINITION.
PUBLIC SECTION.
  data : i_num type i value 5.
  class-data :   
    s_num type i value 6 .
ENDCLASS.
CLASS c1 IMPLEMENTATION.
ENDCLASS.
START-OF-SELECTION.
DATA : oref1 TYPE REF TO c1 .
CREATE OBJECT : oref1.
write:/5 oref1->i_num.
write:/5 c1=>s_num .
write:/5 oref1->s_num.
                         Instance, self-referenced, and static methods can all be called dynamically; the class name for static methods can also be determined dynamically:
u2022     oref->(method)
u2022     me->(method)
u2022     class=>(method)
u2022     (class)=>method
u2022     (class)=>(method)

Similar Messages

  • 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

  • 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

  • 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

  • Regarding Narrow casting

    Hi Experts,
    Here i am giving one program about narrow casting in which i am not able to access the method called 'fasting', but here i am able to access dynamically.
    So, while doing narrow casting may i know that only dynamically we can able to access that method?
    and may i know the clear picture of wide castening & narrow castening with example.
    Please help it out.
    REPORT  Z15704_NARROWING.
    CLASS lcl_animal DEFINITION.
       PUBLIC SECTION.
         METHODS: hungry.
         ENDCLASS.
         CLASS lcl_lion DEFINITION INHERITING FROM lcl_animal.
            PUBLIC SECTION.
             METHODS: hungry REDEFINITION,
                     fasting.
             ENDCLASS.
             CLASS lcl_animal IMPLEMENTATION.
               METHOD hungry.
                   WRITE: / 'An animal is hungry'.
                    ENDMETHOD.
                    endclass.
                      "hungryENDCLASS.
    CLASS lcl_lion IMPLEMENTATION.
      METHOD hungry .
         WRITE: / 'A Lion (King of Jungle) is hungry.'.
          ENDMETHOD.                    "hungry  METHOD fasting.
          METHOD fasting.
           WRITE: / 'Stop running. Lion is on Fasting today.'.
           ENDMETHOD.
           ENDCLASS.
           START-OF-SELECTION.
            DATA: lo_animal TYPE REF TO lcl_animal,
                      lo_lion   TYPE REF TO lcl_lion.
           " ** ANIMAL object without NARROW casting
            WRITE: / 'Animal - without NARROW casting'.
             CREATE OBJECT lo_animal.
               CALL METHOD lo_animal->hungry( ).
              CLEAR lo_animal.
              "** ANIMAL object with NARROW CASTING  SKIP 2.
               WRITE: / 'Animal -  NARROW casting from LION'.
               CREATE OBJECT lo_lion.
                lo_animal = lo_lion.
                CALL METHOD lo_animal->hungry( ).
                CALL METHOD lo_animal->fasting( ).
    when i call  this method dynamically CALL METHOD lo_animal->('fasting'). i am able to access.
    Thanks,
    Radhika

    In Narrow casting, we create a object reference to the Subclass (LO_LION) first and than we assign that object reference to the reference of the Superclass (LO_ANIMAL). Here we have moved from more specific object to less specific object.
    Refer: http://help-abap.blogspot.com/2008/09/abap-objects-narrowing-cast-upcasting.html
    In widening cast, we create a object referece to the superclass (LO_ANIMAL)  first and than we assign the object reference to the Subclass (LO_LION). Here we move from General object to Specific object. As the principal of the inheritance, every Subobject (LO_LION) will have more attributes/properties than the General object (LO_ANIMAL). So, it would not be possilbe to just create LO_ANIMAL and move to LO_LION. So, when we do the Widening cast, we need to first use the narrow casting somewhere in the program to assign proper proerties of subobject (LO_LION) to Superobject (LO_ANIMAL). Than you will successfully move that reference back to Superobject (LO_ANIMAL) to different subobject (LO_LION2).
    Refer: http://help-abap.blogspot.com/2008/09/abap-objects-widening-cast-down-casting.html
    Regards,
    Naimesh Patel

  • Type casting in OOPS ABAP

    Hi Team,
                 Could any one explain me about Type casting used in oops abap and in what circumstances it is
    used with an example.
    Regards,
    Pradeep P.

    Hi,
    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.
    Down-cast (Narrowing Cast)
    Variables of the type “reference to superclass” can also refer to subclass instances
    at runtime. You may now want to copy such a reference (back) to a suitable
    variable of the type “reference to subclass”.
    If you want to assign a superclass reference to a subclass reference, you must
    use the down-cast assignment operator MOVE ... ?TO ... or its short form
    ?=. Otherwise, you would get a message stating that it is not certain that all
    components that can be accessed syntactically after the cast assignment are
    actually available in the instance. As a rule, the subclass class contains more
    components than the superclass.
    After assigning this type of reference (back) to a subclass reference to the
    implementing class, clients are no longer limited to inherited components: In the
    example given here, all components of the LCL_TRUCK instance can be accessed
    (again) after the assignment using the reference R_TRUCK2.
    The view is thus usually widened (or at least unchanged). That is why we describe
    this type of assignment of reference variables as down-cast. There is a switch
    from a view of a few components to a view of more components. As the target
    variable can accept less dynamic types after the assignment, this assignment is
    also called Narrowing Cast
    Reward if helpfull,
    Naresh.

  • Object casting: confusion in ABAP Objects: Complete Reference book

    Hi,
    During Object Assignments using casting, is a Type Test carried out during the syntax check or at runtime?
    A.5.2.2 (page 1008) of 'ABAP Objects: The Complete Reference' says about Widening Cast: "...you must check at runtime...". However on the next page under A.5.3.2 it says of Widening Cast in Data References: "The syntax check precludes...".
    A.5.4 (page 1010) concerns Assignments between Object Reference Variables, but makes no mention of whether checks are carried out by a syntax check or at runtime.
    Also nowhere does it mention when Type Tests for Narrow casting takes place. Can anyone clear my confusion please? Unfortunatly I don't know enough about this stuff to test by writing some code.
    Thanks.

    William,
    Your questions can be answered by the following rule for object references, which I found in the book "ABAP Objects" by Horst Keller and Sascha Krüger:
    "... that the static type of the target variable must be equal to or more general than the dynamic type of the source variable."
    Here "static type" means the type with which an object reference variable is declared. "Dynamic type" is the type that the object reference variable has at runtime. The dynamic type of an object reference is always more special than its static type, otherwise a runtime error occurs.
    With this rule all your questions can be answered:
    1. The Narrowing Cast is always checked during the syntax check. Example:
    DATA o_ref1 TYPE REF TO object.
    DATA o_ref2 TYPE REF TO class_1.
    o_ref1 = o_ref2.  
    Here the reference o_ref2 has a dynamic type "class_1" or a subclass of it, which is narrower than its static type "class_1", which is narrower than the static type "object" of the reference o_ref1. Therefore, the syntax check says that the assignment is OK.
    2. The Widening Cast is always checked at runtime and requires an assignment using the operator ?=. If you use the operator = in the assignment, a syntax error occurs. Therefore the following  example produces a syntax error (try it yourself):
    DATA o_ref1 TYPE REF TO object.
    DATA o_ref2 TYPE REF TO class_1.
    o_ref2 = o_ref1.  
    The correction for this syntax error is:
    DATA o_ref1 TYPE REF TO object.
    DATA o_ref2 TYPE REF TO class_1.
    o_ref2 ?= o_ref1.
    Now the syntax check is satified, and the correctness of the widening cast is checked at runtime.
    Kind regards,
    Michael Kraemer
    Message was edited by: Michael Kraemer

  • 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 的疑问...

    请教大家一个问题。
    在 ABAP Keyword Documentation 中对 MOVE 的说明中有这样一段话:
    Both these statements assign the content of the operand source to the data object destination. The variants with the addition TO or the assignment operator = are valid for all assignments between operands that are not reference variables, and for assignments between reference variables for which the static type of source is more specific than or the same as the static type of destination (narrowing cast).
    但是在 ABAP Glossay 中对narrowing 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.
    这两段对于narrowing cast的描述是相反的,哪个是正确的?谢谢!

    谢谢您的回复。但是不好意思,我还是没有明白。
    正如您所说的:
    第一段说的是操作符 = 或者语法MOVE...TO...的概念,第二段说的是 ?= 或MOVE...?TO..
    但是到底哪个是narrowing cast?
    第一段说 ...(narrowing cast)。=> 它是narrowing cast
    第二段说 Also called a narrowing cast, a down cast ... => 它也是 narrowing cast,又称 down cast
    您说 不满足以上任何一个Narrowing Casting条件的,要使用Widening Casting(Down Casting)  => narrowing cast 和 down cast 是相反的

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

  • Doubts in narrow casting

    I was looking for narrow casting examples to understand concepts better.
    what i have seen everywhere is that
    after narrow casting that i.e assigining/copying child object to parent object we can use parent object to
    call method  which exits in sub class though redefined (of course it also exists in super class).
    Till here its fine.
    But we can't use parent variable to call method in subclass which does not exist in super class.
    it's showing syntax error but a little change in that have made its syntax correct.
    Take a look at this example....
    REPORT  ZNEWOO6.
    *       CLASS vehicle DEFINITION
    class vehicle definition.
       public section.
         methods: m1 ,
         m2.
    endclass.                    "vehicle DEFINITION
    *       CLASS vehicle IMPLEMENTATION
    class vehicle implementation.
       method m1.
         write /'method m1 super class imple.'.
       endmethod.                    "m1
       method m2.
         write /'method m2 super class imple.'.
       endmethod.                    "m1
    endclass.                    "vehicle IMPLEMENTATION
    *       CLASS truck DEFINITION
    class truck definition inheriting from vehicle.
       public section.
         methods:
         m2 redefinition,
         m4.
    endclass.                    "truck DEFINITION
    *       CLASS truck IMPLEMENTATION
    class truck implementation.
       method m2 .
         write /'method m2 redefination sub class imple.'.
       endmethod.                    "m2
       method m4.
    *      method m1.
         write /'method m4 sub class imple.'.
    *  endmethod.
       endmethod.                    "m4
    endclass.                    "truck IMPLEMENTATION
    start-of-selection .
       data : o_super type ref to vehicle,
             o_sub type ref to truck.
       create object :o_super, o_sub.
       call method o_super->m1.
       call method o_sub->m1.
       call method o_super->m2( ).
       o_super = o_sub."up/narrow casting "assigning child to parent
    *o_sub ?= o_super. "down/wide casting
       create object o_super.
       call method o_super->m2.
       call method o_sub->m2.
       "not possible to access those
    *method which are not defined in super class
    call method o_super->m4. "throw a syntax error
    call method o_super->('m4'). "works fine WHY!!!!!! "Even though m4 is not defined in super class

    Hello Abaper,
    when u assign subclass obj to super class its narrow casting,
    but when u create a new object create object o_super.
    it call the old reffernce so o_super call its own m2 instead of subclass m2
    modified code
    *& Report  ZTESTSWADHIN1
    REPORT ZTESTSWADHIN1.
    *       CLASS vehicle DEFINITION
    class vehicle definition.
       public section.
         methods: m1 ,
         m2.
    endclass.                    "vehicle DEFINITION
    *       CLASS vehicle IMPLEMENTATION
    class vehicle implementation.
       method m1.
         write /'method m1 super class imple.'.
       endmethod.                    "m1
       method m2.
         write /'method m2 super class imple.'.
       endmethod.                    "m1
    endclass.                    "vehicle IMPLEMENTATION
    *       CLASS truck DEFINITION
    class truck definition inheriting from vehicle.
       public section.
         methods:
         m2 redefinition,
         m4.
    endclass.                    "truck DEFINITION
    *       CLASS truck IMPLEMENTATION
    class truck implementation.
       method m2 .
         write /'method m2 redefination sub class imple.'.
       endmethod.                    "m2
       method m4.
    *      method m1.
         write /'method m4 sub class imple.'.
    *  endmethod.
       endmethod.                    "m4
    endclass.                    "truck IMPLEMENTATION
    start-of-selection .
       data : o_super type ref to vehicle,
             o_sub type ref to truck.
       create object :o_super, o_sub.
       call method o_super->m1.
       call method o_sub->m1.
       call method o_super->m2( ).
       o_super = o_sub."up/narrow casting "assigning child to parent
    *o_sub ?= o_super. "down/wide casting
    *   create object o_super.
       call method o_super->m2.
       call method o_sub->m2.
    For Details Have alook
    Check o_sub and o_super value..\
    Hope this help.

  • Narrow Casting

    Hi all,
    Can anybody please tell the usuage of narrow casting.
    preferable with simple code.
    Anirban Bhattacharjee

    Hi,
    Narrowing Cast
    If the static type of the target variable is less specific or the same as the static type of the source variable, assignment is always possible. In comparison to the source variable, the target variable knows the same or fewer attributes of the dynamic type. As a result, this assignment is referred to as narrowing cast. A narrowing cast is possible in all ABAP statements in which the content of a data object is assigned to another data object. These include, for example, assignments with the normal assignment operator (=), the insertion of rows in internal tables, or the transfer from actual to formal parameters.
    This means a ref object used is of a child. Now here technically speaking you can call all the methods of the parent class as well as of the child class. So in this case, at runtime if the child object point to a prent object then it will cause an issue if a method specific to a child is called.For the compiler it is not possible to detect this at compile time, like in the above case and therefore a runtime exception is possible.
    Variables of the type reference to superclass can also refer to subclass instances
    at runtime. You may now want to copy such a reference (back) to a suitable
    variable of the type reference to subclass.
    If you want to assign a superclass reference to a subclass reference, you must
    use the down-cast assignment operator MOVE ... ?TO ... or its short form
    ?=. Otherwise, you would get a message stating that it is not certain that all
    components that can be accessed syntactically after the cast assignment are
    actually available in the instance. As a rule, the subclass class contains more
    components than the superclass.
    After assigning this type of reference (back) to a subclass reference to the
    implementing class, clients are no longer limited to inherited components: In the
    example given here, all components of the LCL_TRUCK instance can be accessed
    (again) after the assignment using the reference R_TRUCK2.
    The view is thus usually widened (or at least unchanged). That is why we describe
    this type of assignment of reference variables as down-cast. There is a switch
    from a view of a few components to a view of more components. As the target
    variable can accept less dynamic types after the assignment, this assignment is
    also called Narrowing Cast
    Reward points if useful.
    Best Regards,
    Sekhar

  • Create RSS feed for Narrow casting

    We are using narrow casting and we can stream content to it using an RSS-feed.
    We want to do the following: - Create an rss feed of an exchange (mailbox or calendar) using a script. I think it is just like this link. Or as shown below: 
    ###Code from http://poshcode.org/?show=669
    # Creates an RSS feed
    # Parameter input is for "site": Path, Title, Url, Description
    # Pipeline input is for feed items: hashtable with Title, Link, Author, Description, and pubDate keys
    Function New-RssFeed
    param (
    $Path = "$( throw 'Path is a mandatory parameter.' )",
    $Title = "Site Title",
    $Url = "http://$( $env:computername )",
    $Description = "Description of site"
    Begin {
    # feed metadata
    $encoding = [System.Text.Encoding]::UTF8
    $writer = New-Object System.Xml.XmlTextWriter( $Path, $encoding )
    $writer.WriteStartDocument()
    $writer.WriteStartElement( "rss" )
    $writer.WriteAttributeString( "version", "2.0" )
    $writer.WriteStartElement( "channel" )
    $writer.WriteElementString( "title", $Title )
    $writer.WriteElementString( "link", $Url )
    $writer.WriteElementString( "description", $Description )
    Process {
    # Construct feed items
    $writer.WriteStartElement( "item" )
    $writer.WriteElementString( "title", $_.title )
    $writer.WriteElementString( "link", $_.link )
    $writer.WriteElementString( "author", $_.author )
    $writer.WriteStartElement( "description" )
    $writer.WriteRaw( "<![CDATA[" ) # desc can contain HTML, so its escaped using SGML escape code
    $writer.WriteRaw( $_.description )
    $writer.WriteRaw( "]]>" )
    $writer.WriteEndElement()
    $writer.WriteElementString( "pubDate", $_.pubDate.toString( 'r' ) )
    $writer.WriteElementString( "guid", $homePageUrl + "/" + [guid]::NewGuid() )
    $writer.WriteEndElement()
    End {
    $writer.WriteEndElement()
    $writer.WriteEndElement()
    $writer.WriteEndDocument()
    $writer.Close()
    ### end code from http://poshcode.org/?show=669
    ## Get the Mailbox to Access from the 1st commandline argument
    $MailboxName = $args[0]
    ## Load Managed API dll
    Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"
    ## Set Exchange Version
    $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1
    ## Create Exchange Service Object
    $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)
    ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials
    #Credentials Option 1 using UPN for the windows Account
    $psCred = Get-Credential
    $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())
    $service.Credentials = $creds
    #Credentials Option 2
    #service.UseDefaultCredentials = $true
    ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates
    ## Code From http://poshcode.org/624
    ## Create a compilation environment
    $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
    $Compiler=$Provider.CreateCompiler()
    $Params=New-Object System.CodeDom.Compiler.CompilerParameters
    $Params.GenerateExecutable=$False
    $Params.GenerateInMemory=$True
    $Params.IncludeDebugInformation=$False
    $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null
    $TASource=@'
    namespace Local.ToolkitExtensions.Net.CertificatePolicy{
    public class TrustAll : System.Net.ICertificatePolicy {
    public TrustAll() {
    public bool CheckValidationResult(System.Net.ServicePoint sp,
    System.Security.Cryptography.X509Certificates.X509Certificate cert,
    System.Net.WebRequest req, int problem) {
    return true;
    $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
    $TAAssembly=$TAResults.CompiledAssembly
    ## We now create an instance of the TrustAll and attach it to the ServicePointManager
    $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
    [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll
    ## end code from http://poshcode.org/624
    ## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use
    #CAS URL Option 1 Autodiscover
    $service.AutodiscoverUrl($MailboxName,{$true})
    "Using CAS Server : " + $Service.url
    #CAS URL Option 2 Hardcoded
    #$uri=[system.URI] "https://casservername/ews/exchange.asmx"
    #$service.Url = $uri
    ## Optional section for Exchange Impersonation
    #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)
    # Bind to the Contacts Folder
    $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
    $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
    $psPropset = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)
    #Define ItemView to retrive just 50 Items
    $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(50)
    $fiItems = $service.FindItems($Inbox.Id,$ivItemView)
    [Void]$service.LoadPropertiesForItems($fiItems,$psPropset)
    $feedItems = @()
    foreach($Item in $fiItems.Items){
    "processing Item " + $Item.Subject
    $PostItem = @{}
    $PostItem.Add("Title",$Item.Subject)
    $PostItem.Add("Author",$Item.Sender.Address)
    $PostItem.Add("pubDate",$Item.DateTimeReceived)
    $PostItem.Add("link",("https://" + $service.Url.Host + "/owa/" + $Item.WebClientReadFormQueryString))
    $PostItem.Add("description",$Item.Body.Text)
    $feedItems += $PostItem
    $feedItems | New-RssFeed -path "c:\temp\Inboxfeed.xml" -title ($MailboxName + " Inbox")
    But it is a Exchange Management Shell script an we would like to execute it like a .php file.
    Can anyone help me with this please?
    I would like to thank you in advance.
    Kind regards,
    Jordi Martin Lago

    That's not a Exchange Management Shell script its just a normal powershell script that uses the EWS Managed API
    http://msdn.microsoft.com/en-us/library/dd633710(v=exchg.80).aspx . So you can run it from any workstation or server where you have powershell and the Managed API library installed.
    You will need to update the line
    Add-Type -Path
    "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"    
    To
    Add-Type -Path
    "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"    
        To cater for the latest version of the Managed API.
      You can scheduled powershell scripts to run using the Task Scheduler eg
    http://community.spiceworks.com/how_to/show/17736-run-powershell-scripts-from-task-scheduler
    Cheers
    Glen

Maybe you are looking for

  • Unable to connect video/audio chat. They are 'declining'

    Just this week I am unable to connect to anyone over video or audio chat. An error keeps coming up on both ends that the user is declining the invitation moments after it states it is 'connecting'. I have tried changing the connection ports to 80 and

  • OS 10.4.11 won't open IPod Mini

    I connected my IPod Mini to  my Mac OS 10.4.11 Powerbook, and ITunes opened, and the IPod screen was in Do Not Disconnect mode, but there were no IPod icons in the source , and no downloading was taking place. I am running ITunes 9.0.2. Thanks for an

  • How can I change the place of a photo in iPhoto?

    How can I change the place label of a photo in iPhoto?

  • How can we give values to the variable

    Oracle Forms6i Hai All I am generating an daily attendance regarding shift basis.In that i have written an ifelse condition it work successfull and but it fetches only 350 row out of 800. I have declared a variable and i need to know how to assign va

  • Slide timing in iDVD slideshow

    Is there any way to customize the time per slide for an iDVD slideshow? The 1, 3, and 5 second choices aren't adequate. Thanks.