Cast in oops

what is cast? what is narrowing cast?what is widening  cast?what is ME? plz explai me with good examples.

NARROWING CAST
One of the significant principles of inheritance is that an instance from a subclass can be used in every
context in which an instance from the superclass appears. This is possible because the subclass has
inherited all components from the superclass and therefore has the same interface as the superclass. The
user can therefore address the subclass instance in the same way as the superclass instance.
Variables of the type “reference to superclass” can also refer to subclass instances at runtime.
The assignment of a subclass instance to a reference variable of the type “reference to superclass” is
described as a narrowing cast, because you are switching from a view with more detail to a view with less
detail.
The description “up-cast” is also used.
What is a narrowing cast used for? A user who is not interested in the finer points of cargo or passenger
planes (but only, for example, in the tank gauge) does not need to know about them. This user only needs
to work with (references to) the lcl_airplane class. However, in order to allow the user to work with cargo or
passenger planes, you would normally need a narrowing cast.
example
DATA: airplane TYPE REF TO lcl_airplane,
cargo_airplane TYPE REF TO lcl_cargo_airplane,
level TYPE ty_level.
CREATE OBJECT cargo_airplane.
* Subclass instance understands the same messages
* as superclass instance
CALL METHOD cargo_airplane->get_fuel_level RECEIVING re_level = level.
* Narrowing Cast
airplane = cargo_airplane.
* Using the subclass instance in the superclass context
CALL METHOD airplane->get_fuel_level RECEIVING re_level = level.
After the narrowing cast you can use the airplane reference to access the components of the cargo plane
instance that were inherited from lcl_airplane, obviously in some cases with the limitations entailed by their
visibility. You can no longer access the cargo-plane-specific part of the instance (cargo in the above
example) using the airplane reference.
A reference variable always has two types: static and dynamic:
- The static type of a reference variable is determined by variable definition using TYPE REF TO. It cannot
and does not change. It establishes which attributes and methods can be addressed
- The dynamic type of a reference variable is the type of the instance currently being referred to, it is
therefore determined by assignment and can change during the program run. It establishes what coding is
to be executed for redefined methods.
In the example, the static type of the airplane variable is always ‘REF TO lcl_airplane’, but its dynamic type
after the cast is ‘REF TO lcl_cargo_airplane’.
The reference ME can be used to determine the dynamic type in the Debugger.
imp
The static type of a reference variable
Is determined using TYPE REF TO
Remains constant throughout the program run
Establishes which attributes and methods can be
addressed
The dynamic type of a reference variable
Is determined by assignment
Can change during the program run
Establishes what coding is to be executed for redefined
methods
WIDENING CAST
The type of case described above is known as a widening cast because it changes the view to one with
more details. The instance assigned (a cargo plane in the above example) must correspond to the object
reference (cargo_airplane in the above example), that is, the instance must have the details implied by the
reference.
This is also known as a “down cast”.
The widening cast in this case does not cause an error because the reference airplane actually points to an
instance in the subclass lcl_cargo_airplane. The dynamic type is therefore ‘REF TO lcl_cargo_airplane’.
EXAMPLE
DATA: airplane TYPE REF TO lcl_airplane,
cargo_airplane TYPE REF TO lcl_cargo_airplane,
cargo_airplane2 TYPE REF TO lcl_cargo_airplane.
CREATE OBJECT cargo_airplane.
airplane = cargo_airplane.
imp about widening cast
Cannot be checked statically
If unsuccessful, ends with a catchable runtime
CATCH SYSTEM-EXCEPTION MOVE_CAST_ERROR = 4.
cargo_airplane ?= airplane.
ENDCATCH.
IF SY-SUBRC EQ 4.
ENDIF.
The widening cast logically represents the opposite of the narrowing cast. The widening cast cannot be
checked statically, only at runtime. The Cast Operator “?=” (or the equivalent “MOVE ... ?TO …”) must be
used to make this visible.
With this kind of cast, a check is carried out at runtime to ensure that the current content of the source
variable corresponds to the type requirements of the target variables. In this case therefore, it checks that
the dynamic type of the source reference airplane is compatible with the static type of the target reference
cargo_airplane. If it is, the assignment is carried out. Otherwise the catchable runtime error
“MOVE_CAST_ERROR” occurs, and the original value of the target variable remains the same.
cheers
sharad
Edited by: sharad narayan on Apr 16, 2008 1:33 PM

Similar Messages

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

  • 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

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

  • Casting in ABAP Objects

    Why the cast error generates only in Widening cast?

    Hi Shyam,
    WELCOME TO SDN!!!
    Please check this link
    http://abapprogramming.blogspot.com/2007/10/oops-abap-8.html
    The widening cast in this case does not cause an error because the reference airplane actually points to an instance in the subclass lcl_cargo_airplane. The dynamic type is therefore u2018REF TO lcl_cargo_airplaneu2019.
    Here the widening cast produces the MOVE_CAST_ERROR runtime error that can be caught with u201CCATCH ... ENDCATCHu201D, because the airplane reference does not point to an instance in the subclass lcl_cargo_airplane, but to a u201Cgeneral airplane objectu201D. Its dynamic type is therefore u2018REF TO lcl_airplaneu2019 and does not correspond to the reference type cargo_airplane.
    The widening cast logically represents the opposite of the narrowing cast. The widening cast cannot be checked statically, only at runtime. The Cast Operator u201C?=u201D (or the equivalent u201CMOVE ... ?TO u2026u201D) must be used to make this visible.
    With this kind of cast, a check is carried out at runtime to ensure that the current content of the source variable corresponds to the type requirements of the target variables. In this case therefore, it checks that the dynamic type of the source reference airplane is compatible with the static type of the target reference cargo_airplane. If it is, the assignment is carried out. Otherwise the catchable runtime error u201CMOVE_CAST_ERRORu201D occurs, and the original value of the target variable remains the same.
    Best regards,
    raam

  • Creating ALV reports using OOP concept

    After creating many reports i found out that 90% of the coding in a report is copy paste i.e. only 10% of coding effort is required which includes
        creating the custom data types and internal table variables  ...
        populating the data
        creating screen,GUI status and GUI title
    Just copy paste the below code and do as stated  :
    *ALV TEMPLATE
    *create screen no. 2000
    *change flow logic in screen if necessary
    *create GUI status and GUI title
    *change selection texts and text symbols*
    REPORT  Y_TEMPLATE_ALV.
    TABLES : ."use if range of values required on selection screen.
    DATA: zcl_alvgrid        TYPE REF TO cl_gui_alv_grid,
           zcl_ccontainer     TYPE REF TO cl_gui_docking_container,
           wa_layout    TYPE lvc_s_layo,
           it_fieldcat  TYPE STANDARD TABLE OF lvc_s_fcat,
           wa_fieldcat  TYPE lvc_s_fcat,
           z_document         TYPE REF TO cl_dd_document,
           o_docking TYPE REF TO cl_gui_docking_container,"Docking Container
           o_split TYPE REF TO cl_gui_easy_splitter_container, "Splitter
           o_top_container TYPE REF TO cl_gui_container,   "Top Container
           o_bottom_container TYPE REF TO cl_gui_container."Bottom Container
    TYPES : BEGIN OF TY_FINAL,
    "All columns which are to be displayed in the report should be included here
    END OF TY_FINAL.
    *Add additional Internal Tables's if data is to be extracted from multiple tables
    *Then loop at main table and Read the other tables
    DATA :IT_DATA TYPE STANDARD TABLE OF , "data extracted from tables can be stored in this internal table variable ..
           WA_DATA TYPE ,
           iT_alv      TYPE STANDARD TABLE OF TY_FINAL, " pass to  the method SET_TABLE_FOR_FIRST_DISPLAY of class
    ZCL_ALVGRID [Already done ; its  just fyi]
           WA_alv      TYPE                   TY_FINAL.
    DATA :V_CLN(255) TYPE C, " For no. of records
           V_LINE TYPE I. " for conversion of integer to character
    *                 Selection Screen                                     *
    SELECTION-SCREEN BEGIN OF BLOCK B1 WITH FRAME TITLE TEXT-001.
    PARAMETERS:
    SELECT-OPTIONS: " PARAMETERS and Range on selection screen
    SELECTION-SCREEN END OF BLOCK B1.
    AT SELECTION-SCREEN OUTPUT.
    *                        START  OF  SELECTION                          *
    START-OF-SELECTION.
    *  SELECT * FROM INTO CORRESPONDING FIELDS OF TABLE IT_DATA WHERE ....in ....
       IF SY-SUBRC = 0.
         LOOP AT IT_DATA INTO WA_DATA.
           MOVE-CORRESPONDING WA_DATA TO wa_alv. " if data is fetched from only one table
           APPEND wa_alv TO it_alv.
           CLEAR : wa_alv,WA_DATA.
         ENDLOOP.
         DESCRIBE TABLE it_alv LINES V_LINE.
         V_CLN = V_LINE.
       ENDIF.
    END-OF-SELECTION.
       PERFORM DISPLAY_ALV.
    *&      Module  STATUS  OUTPUT
    *       text
    MODULE STATUS_2000 OUTPUT.
       SET PF-STATUS 'STATUS'.
       SET TITLEBAR 'ALV'.
    *  ** Creating Docking Container
       CREATE OBJECT o_docking
       EXPORTING
    *    side = cl_gui_docking_container=>dock_at_right
         ratio = '95'.
       IF sy-subrc EQ 0.
    * Splitting the Docking container
         CREATE OBJECT o_split
         EXPORTING
           parent        = o_docking
           sash_position = 05 "Position of Splitter Bar (in Percent)
           with_border   = 0. "With Border = 1 Without Border = 0
    *   Placing the containers in the splitter
         o_top_container = o_split->top_left_container .
         o_bottom_container = o_split->bottom_right_container .
    *   Creating the document
         CREATE OBJECT z_document
         EXPORTING
           style = 'ALV_GRID'.
       ENDIF.
    * Calling the methods for dynamic text
       CALL METHOD z_document->add_text
       EXPORTING
         TEXT         = 'No. of Records:'
         sap_emphasis = cl_dd_area=>strong. " For bold
    * Adding GAP
       CALL METHOD z_document->add_gap
       EXPORTING
         width = 10.
    * Adding Text
       CALL METHOD z_document->add_text
       EXPORTING
         TEXT = v_cln.
    * Adding Line
       CALL METHOD z_document->new_line.
    * Display the data
       CALL METHOD z_document->display_document
       EXPORTING
         parent = o_top_container.
       IF zcl_alvgrid IS INITIAL .
    *----Creating ALV Grid instance
         CREATE OBJECT zcl_alvgrid
         EXPORTING
           i_parent          = o_bottom_container
         EXCEPTIONS
           error_cntl_create = 1
           error_cntl_init   = 2
           error_cntl_link   = 3
           error_dp_create   = 4
           OTHERS            = 5.
         IF sy-subrc <> 0.
           MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
           WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
         ENDIF.
    * Calling the method of ALV to process top of page
         CALL METHOD zcl_alvgrid->list_processing_events
         EXPORTING
           i_event_name = 'TOP_OF_PAGE'
           i_dyndoc_id  = z_document.
    * Preparing field catalog.
         PERFORM T_FIELDCAT USING:
                    '1'        'BRNCD'      'BRAND'.
    *          'Column no' 'FIELDNAME' 'Column Heading' 
         WA_LAYOUT-CWIDTH_OPT = 'X'.
         WA_LAYOUT-ZEBRA = 'X'.
         WA_LAYOUT-SEL_MODE =  'A'.
    * Setting table for first display
         CALL METHOD ZCL_ALVGRID->SET_TABLE_FOR_FIRST_DISPLAY
         EXPORTING
           IS_LAYOUT                     = WA_LAYOUT
         CHANGING
           IT_OUTTAB                     = it_alv
           IT_FIELDCATALOG               = IT_FIELDCAT
         EXCEPTIONS
           INVALID_PARAMETER_COMBINATION = 1
           PROGRAM_ERROR                 = 2
           TOO_MANY_LINES                = 3
           OTHERS                        = 4.
         IF SY-SUBRC <> 0.
           MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
           WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
         ENDIF.
       ELSE.
         CALL METHOD ZCL_ALVGRID->REFRESH_TABLE_DISPLAY
         EXCEPTIONS
           FINISHED = 1
           OTHERS   = 2.
         IF SY-SUBRC <> 0.
           MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
           WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
         ENDIF.
       ENDIF.
    ENDMODULE.                 " STATUS  OUTPUT
    MODULE USER_COMMAND_2000 INPUT.
       DATA: V_OK_CODE TYPE SY-UCOMM,
             V_SAVE_OK TYPE SY-UCOMM.
       V_OK_CODE = SY-UCOMM.
       V_SAVE_OK = V_OK_CODE.
       CASE SY-UCOMM.
         WHEN 'BACK'.
           SET SCREEN 1000.
         WHEN 'EXIT'.
           LEAVE program.
         WHEN OTHERS.
           SET SCREEN 1000.
       ENDCASE.
       CLEAR V_SAVE_OK.
       SET SCREEN 0.
       LEAVE SCREEN.
    ENDMODULE.                 " USER_COMMAND_2000  INPUT
    *&      Form  T_FIELDCAT
    *       text
    *      -->x   text
    *      -->y   text
    *      -->z   text
    FORM T_FIELDCAT  USING VALUE(X) TYPE ANY
           VALUE(Y) TYPE ANY
           VALUE(Z) TYPE ANY.
       WA_FIELDCAT-COL_POS = X.
       WA_FIELDCAT-FIELDNAME = Y.
       WA_FIELDCAT-COLTEXT  = Z.
       APPEND WA_FIELDCAT TO IT_FIELDCAT.
       CLEAR WA_FIELDCAT.
    ENDFORM.                      " T_FIELDCAT
    *&      Form  DISPLAY_ALV
    *       text
    *  -->  p1        text
    *  <--  p2        text
    FORM DISPLAY_ALV .
       IF NOT it_alv[] IS INITIAL.
         CALL SCREEN 2000.
       ELSE.
         MESSAGE 'No data for Display' TYPE 'I'.
       ENDIF.
    ENDFORM.                    " DISPLAY_ALV

    Hello Jay,
    Calling methods, creating instances, casting etc are not OOP. When you say you've developed an OO-report you think OO, refer to this blog to see what i mean - Global Data in ABAP OO Programs
    BR,
    Suhas

  • Class cast exception using Finder method

    Hello. I'm new to J2EE. I have set up one entity bean but am having trouble
    with my current one.
    Basically, I have two finder methods:
    public ShareHistory findByPrimaryKey(Integer historyId)
            throws FinderException, RemoteException;
        public Collection findByShare(String shareId)
             throws FinderException, RemoteException; findByPrimaryKey works fine, but findByShare causes a class cast exception in java.lang.String.
    The stack trace in the server logs shows that it is my ejbActivate method in my entity bean causing the problem:
    public void ejbActivate() {
          //String numberString = (String) context.getPrimaryKey();
          //historyId = new Integer(numberString);
        historyId = (Integer) context.getPrimaryKey();
        }The stack trace from my client shows that the class cast exception occurs
    in the client at the System.out.println("shareid" + ": " + sh.getShareId());
    line:
    Collection c = sharesHistoryHome.findByShare("DCAN");
                     Iterator i = c.iterator();
                          while (i.hasNext()) {
                         ShareHistory sh = (ShareHistory) i.next();
                    System.out.println("shareid" + ": " + sh.getShareId());
                    System.out.println("value" + ": " + sh.getValue());
                     System.out.println("time" + ": " + sh.getTime());
                     System.out.println("date" + ": " + sh.getDate());
                     }//whileAs you can see I tried casting to a string in ejbactivate, but that simply causes an Integer class cast exception during findByprimaryKey instead. How do I allow both Integer and String objects to be used?
    Also I am a bit confused as to why the String passed to findByShare(String) is being used in context.getPrimaryKey() in the first place (if that is actually what's happening).

    Oops my FindByShare method was returning a collection of shareId's (strings) instead of a collection of Integer primary keys, which would explain the class cast exception.

  • Module pool program with OOPS

    Hi friends,
    am working on module pool program i want to use oops concept in moduel pool.can any body give me an example in
    module pool with oops .
    Thanks in advance,
    sai.

    Hello,
    we have uses ABAP OO and Classic Dypros in our current projekt a lot.
    It turned out to be the best way to it like this:
    1. Create your Dynpro
    2. Create an Interface that corresponds only to that Dynpro.
    3. In the Modules of the dynpro you only  call Methods from that interface created above, also all checks of Dynprofields etc should be handled in the Implelmentation of the methods. so you do like that:
    Module set_vbeln.
       gi_dynp_class->set_vbeln( gs_sd-vbeln ).
    endmodul.
    gi_dynp_class is from type of your interface.
    4. Create an application class that implements all the methods of the interface with the logic needed.  Using inheritance you can easily reuse the the Dynpro in different contexts with different Application classes behind it.
    5. In PBO of the dynpro you have to make sure that the the variable gi_dynp_class is bound. So you will cast your application class instance to it:
    gi_dynp_class ?= gi_app_class.
    The application class must be instanciates at the beginning of the program before the dynpro is used.
    As a class can implement several interface you can enable you application class for as many dynpros as you want to.
    Hope that helps a bit ...
    Greetings from Hamburg

  • Create a child cast member

    Hi,
    I need to create a dynamic menu for an application. Right
    now I am creating every item as a new cast member:
    newMember = new(#text)
    member(newMember).name = "Item1"
    member(newMember).text = "Blabla"
    What I would like to do, is have an existing cast member with
    the good font, font size, color, etc... and in my lingo script,
    create all my new cast members based on the existing one, so I
    would only need to change the text it contains and not the color,
    size....
    It could also be usefull to do this since I could attach a
    behavior to the existing cast member and then all my new ones would
    have the same behavior attached to them.
    I hope this can be done, sorry if it is obvious, I'm in the
    process of learning Director and Lingo.
    Thanks,
    Pat

    Hi Pat, and welcome to the list.
    As for your question, I'd suggest you work with a single cast
    in general,
    unless it really helps organizing your project.
    Creating members on the fly -as it seems you are doing- is a
    much cleaner
    approach.
    Why don't you create a handler that would accept as arguments
    the formatting
    options and the member they should be applied to?
    Or e.g. two handlers that each would apply some fixed
    formatting to a member
    that is passed to it.
    The less the members, the smaller the project, btw.
    > It could also be useful to do this since I could attach
    a behavior to the
    > existing cast member
    I suppose you are talking about cast member scripts, not
    behaviors. Another
    thing you'd better avoid, since behaviors (scripts attached
    to sprites) are
    more flexible, receive notifications that script members
    don't (like e.g. on
    beginSprite), and are designed for oop (a reference to the
    script
    object -me- is passed as the first argument by the system
    when calling
    behaviors' handlers).
    "PDiLalla" <[email protected]> wrote in
    message
    news:f97p50$rh1$[email protected]..
    > Hi,
    >
    > I need to create a dynamic menu for an application.
    Right now I am
    > creating
    > every item as a new cast member:
    >
    > newMember = new(#text)
    > member(newMember).name = "Item1"
    > member(newMember).text = "Blabla"
    >
    > What I would like to do, is have an existing cast member
    with the good
    > font,
    > font size, color, etc... and in my lingo script, create
    all my new cast
    > members
    > based on the existing one, so I would only need to
    change the text it
    > contains
    > and not the color, size....
    >
    > It could also be usefull to do this since I could attach
    a behavior to the
    > existing cast member and then all my new ones would have
    the same behavior
    > attached to them.
    >
    > I hope this can be done, sorry if it is obvious, I'm in
    the process of
    > learning Director and Lingo.
    >
    > Thanks,
    > Pat
    >

  • Using field symbols in OOPs programming...have ur points.

    Hi all,
    I want to use field symbols in OOPS programming like this...
    But the system is giving me dump....help me.
    START-OF-SELECTION.
    CREATE OBJECT OBJ.
    FIELD-SYMBOLS : <AB> TYPE ANY.
    ASSIGN OBJ TO <AB>.
    CALL METHOD <AB>->add
      EXPORTING
        a      = 4
        b      = 6
      changing
        c      = Z
    WRITE : / Z.

    check the code below
    TYPES: BEGIN OF t_struct,
             col1 TYPE i,
             col2 TYPE i,
           END OF t_struct.
    DATA: dref1 TYPE REF TO data,
          dref2 TYPE REF TO data.
    FIELD-SYMBOLS: <fs1> TYPE t_struct,
                   <fs2> TYPE i.
    CREATE DATA dref1 TYPE t_struct.
    ASSIGN dref1->* TO <fs1>.
    <fs1>-col1 = 1.
    <fs1>-col2 = 2.
    dref2 = dref1.
    ASSIGN dref2->* TO <fs2> CASTING.
    WRITE / <fs2>.
    GET REFERENCE OF <fs1>-col2 INTO dref2.
    ASSIGN dref2->* TO <fs2>.
    WRITE / <fs2>.
    reward points if helpful.........

  • Question about compile-time legality rules for cast conversion

    Hi, In the rules which explain compile-time legality for cast conversion, it is often mentioned the following scenario in the cast conversion of a compile-time type S to a compile-time type T:
    if S is a class type then:
    if T is a class type then either |S| <: |T| or |T| <: |S| or a compile time error occurs. Furthermore, if there exist a supertype X of T and a supertype Y of S such that X and Y are provably distinct parameterized types and that the erasures of X and Y are the same, a compile-time error occurs.
    As regards the quote in bold, I imagine the following scenario:
    1) S <: T and extends Y
    2) Y<T1...Tn>
    3) X<T1..Tn>
    4) T extends X
    Does the above represents a supertype X of T and a supertype Y of S such that X and Y are provenly distinct parameterized types? If that holds, what does it mean that the erasure of X and Y is the same?

    Declarative programing has all but gone the way of
    the doe doe because...
    1: It is not flexible (It is extremely difficult to
    change a complex system in a predetermined way)isn't this the "expert system" model?
    2: It lengthens the development cycle (see item 1)
    3: It normally forces the developer to add many
    things to there code to get things to work, that have
    nothing to do with the intent of the code.more things? the declarations or the declaration processing?
    In its defense (I like a declarative model but, do
    not like being forced into one)...not advocating a forced change in Java
    1: It increases code safety.
    2: It can shorten the development cycle, in certain
    circumstances (especially if it is not overused),
    because it can greatly increase the readability of
    code.
    3: It follows many best practices (although this is
    also possible in a Non-Declarative model).as for best practices what I'd like to see are declarative design patterns, Adapter, Singleton, Factory, Delegate, Strategy, Interpreter, Proxy, Visitor
    too often the design intent is lost in an implementation or design details can only be deduced by class/field/method names, comments, and accompanying docs
    So, if everyone had unlimited time, and an unlimited
    budget, yes declaritive is the way to go. Since that
    is not the case, we filtered out 99% of what it gave
    us, made sure the stuff that was getting in the way
    was removed, and what do you have???
    You guessed it OOA&D.
    Now having said that should we be more declarative? I
    think so, but I will tell you now, REQUIRING
    declarative elements in code is a sure fire way to
    get the majority of development groups to drop the
    language (and I think Java as it stands currently CAN
    be declarative, so if you have one of those unlimited
    budgets, go for it!).no need to require it
    I believe given good (reusable) declarative options, on top of OOP, will become the chosen approach
    reusable design declarations would lessen overall cost and increase readability

  • How to get an exception when casting a generic collection?

    Hi,
    I have a bit of code that looks more or less like this:import java.util.ArrayList;
    import java.util.Collection;
    public class CollectionTest {
         public static void main (String[] args) {
              try {
                   get (Float.class);
              } catch (ClassCastException e) {
                   System.err.println ("Oops");
                   e.printStackTrace (System.err);
              try {
                   Collection<Short> shorts = get (Short.class);
                   for (Short s : shorts) {
                        System.out.println (s);
              } catch (ClassCastException e) {
                   System.err.println ("Oops");
                   e.printStackTrace (System.err);
              try {
                   Collection<Number> numbers = get (Number.class);
                   for (Number number : numbers) {
                        System.out.println (number);
              } catch (ClassCastException e) {
                   System.out.println ("Oops again");
                   e.printStackTrace (System.err);
         public static <T> Collection<T> get (Class<T> clazz) {
              Collection<T> ret = new ArrayList<T> ();
              if (clazz == String.class) {
                   ret.add (clazz.cast ("Test"));
              } else if (clazz == Integer.class) {
                   ret.add (clazz.cast (Integer.valueOf (1)));
              } else if (clazz == Double.class) {
                   ret.add (clazz.cast (Double.valueOf (1.0)));
              } else if (clazz == Float.class) {
                   ret.add (clazz.cast ("Bug")); // Bug here, blatent
              } else if (clazz == Short.class) {
                   ret.add ((T) "Bug"); // Bug here, latent
              } else if (clazz == Number.class) {
                   ret.addAll (get (Integer.class));
                   ret.addAll (get (Double.class));
                   ret.addAll (get (String.class)); // Another bug here, latent
              return ret;
    }Obviously this doesn't compile as-is, I have to add 3 casts towards the end. Then when I add the casts and run the program I discover I have several bugs, some of which are fail-early and some of which lie hidden until the further away from the bug Since I have the type-token, I use it to check the simple cast, but is there any way I can get a failure more or less at the point where the dodgy Collection cast is made?

    OK, sorry not to be clear. My example code is meant to crash on the erroneous casts - clearly a String cannot be cast to a Float, nor a Short. My point is that in one case the code crashes at the point where the cast is made and in another case the code crashes later on. What I want to achieve is this early failure in case of buggy code. Here is a shorter example:import java.util.ArrayList;
    import java.util.Collection;
    public class CollectionTest {     
         public static <T> Collection<T> get (Class<T> clazz) {
              Collection<T> ret = new ArrayList<T> ();
              if (clazz == String.class) {
                   ret.add (clazz.cast ("Test"));
              } else if (clazz == Integer.class) {
                   ret.add (clazz.cast (Integer.valueOf (1)));
              } else if (clazz == Double.class) {
                   ret.add (clazz.cast (Double.valueOf (1.0)));
              } else if (clazz == Number.class) {
                   ret.addAll ((Collection<? extends T>) get (Integer.class));
                   ret.addAll ((Collection<? extends T>) get (Double.class));
                    // This is a bug, but how can I get an exception at this point?
                   ret.addAll ((Collection<? extends T>) get (String.class));
              return ret;
    }If I mistakenly write this code it will compile (with the addition of the appropriate casts). However, my code is buggy and will fail when the user of the collection receives a String when he is expecting a Number. My question is, how can I get my code to fail where I make the erroneous cast? If you look at the code I originally posted I have two casts of the String "Bug", one of which is done by (T) and the other is clazz.cast. The first example fails late and the second fails early - it is this early failure that I would like to achieve, in the case of buggy code, in my example above.
    Am I making sense yet?

  • OOP Generic Object Manager

    Has any of the OOP programmers out there ever developed a generic object manager?  What I mean by this is a an Object in LabVIEW that can hold references to all objects in an application that can be accessed generically through a name input and not via know each individual class type.  I have been trying to create a class that essentially has as its attributes an array of LV Objects since all objects descend from this class.  I am struggling with getting the specific class back from the generic class.  If I probe the array it shows the class specific type.
    So what I am trying to do is search an array of standard LabVIEW Objects for a specific LabVIEW type.  Here I created an array of LabVIEW object by casting specific classes to the most generic class - LabVIEW Object.  Then I want to search an array for a specific class by taking a specific class constant and casting it to a more generic class.  It seems like it keeps the reference information (ID).
    Any thoughts?

    LV2009 added a function which is probably crucial to delivering a nice solution to this problem. The function is called Preserve Run-time Class. It allows you to propogate the strict type of an object through a subVI that is coded to operate on a more generic class type.
    Here's an example written in LV2009 for a simple class that stores any other LV class object by name.
    Jarrod S.
    National Instruments
    Attachments:
    Temp.zip ‏33 KB

  • OOP for abap

    good morning to all sap experts,
    i have a question for any OOP programmers in abap. i have been working in abap for over 12 years, but have not yet transitioned to oop. but, since we have been upgrading to ecc 6.0, i am constantly working with oop classes, and objects. maybe someone can answer these questions, and also point me in the right direction online, to educate myself.
    i have a class that is called CL_WTY_CLAIM and it is running a method called get_direct_references. within get_direct_references, this line of code is running.
    co_ltext ?= co_ext_objects->get_ext_buffered_object(
                                      co_ltext_class_id ).
    firstly, what does "?=" mean?
    secondly, if i go to get_ext_buffered_object, i find the following code.
    ro_object = co_ext_objects->get_ext_buffered_object( io_id ).
    how/where is the code running to fill the initial co_ltext field?
    please and thank you.

    thanks for the quick reply. i think i understand the down cast function.
    when i debug the code at the point of the following:
    co_ltext ?= co_ext_objects->get_ext_buffered_object(
                                      co_ltext_class_id ).
    it goes to the get_ext_buffered_object method, and i see the following:
    data:
        ls_ext_object type t_ext_object.
      read table ct_external_objects into ls_ext_object
        with table key id = io_id.
      ro_object = ls_ext_object-object.
    can you easily tell me how the ct_external_objects table is populated? i know that the table is in another class "CL_WTY_BUFFER_EXT_CNTL" and it is a attribute of that class, but i do not know how it is populated. do you have another link to show me a easy way to determine how a table is populated?
    the issue i am having is that this table does not always have the text info i am looking for. i would like to review their code to see if it is a data problem, or a code problem.
    thanks again.

  • OOP Programming Question

    Hi,
    Im new to oop in as3.0, just finished my first oop application but there is one thing that i don't understand.
    If i have movieclips on the stage and i want for ex. the display class to control there position and size then
    i need to send it from the document class to the display class using a public method on the display class.
    but after developing my first application i got to a point that all of my methods on the display class were public
    and i used a lot of repatitive code.... ive been told that i need to avoid public methods and try and keep most of the methods in
    the different classes private but the only way to do it is to find a way to pass the movie clip instance to the actual class and control it
    and this way most of the methods in the class will be private and the code on the document class will be a lot more cleaner, but i dont really
    know how to pass a display object to a different class and use it without passing it to a public method through the document class.

    I'm relatively new to OOP programming, so please
    excuse this newbish question :).
    I've been assigned to take over for a co-worker that
    has left for vacation. A class that he wrote is
    partially implemented, so I'm supposed to finish it
    up.
    One class in particular, his constructor is empty.That's fine, if that's what makes sense. I'd have one constructor that set all the private data members. Other constructors would call it using sensible defaults where needed.
    If the ctor is empty and data members are null, that's very bad. An object should be 100 percent ready to go when you create it.
    And to set the instance variables, the user class is
    setting them directly, not through accessor methods.So the data members are public? Oh, my. Where's the encapsulation?
    This seems like a bad idea, and defeats the whole
    purpose of encapsulation. Indeed. Sounds like you know more than your co-worker.
    I wanted to re-do some of the code, but are there any
    good reasons as to why he might be doing this?If it's a DTO C-struct with no other purpose than ferrying data it might be acceptable. I would say it's not acceptable, but that's my opinion.
    Saving some overhead maybe?No, the "overhead" is probably not measurable. I wouldn't optimize such a thing without data that told me it was the bottleneck, and I'd make sure that this "fix" did address the problem before I cast it in stone.
    %

Maybe you are looking for