Why do we require Type Casting?

Hi,
In short can you guys share your experience and expalin me why and when do we require type casting of objetcs.I would appericiate if i get a simple application as an example.
regards
Vicky

Hi,
In short can you guys share your experience and
nd expalin me why and when do we require type casting
of objetcs.I would appericiate if i get a simple
application as an example.
regards
VickyWhy do you need this again?
Well, really you need type casting because you want to be able to check for errors at compile time. You actually don't need any type casting if you just wait to link all your code at runtime.
Normally your function calls are checked vs the real 'type' at compile time to see if you are calling the function with the proper types and number of arguments. same with returning. However, you don't have to do this, just look at any scripting language. All that is checked at runtime.
Problems with not checking at compile time are mostly speed and corectness errors. The runtime might decide to call a different function then the one you wanted because at runtime a 'better' one was found. Of course now you would get a link error at runtime and the code would just not execute. There would be problems with overriding and hiding of functions, etc.
Also, since you can't link ahead of time it takes longer to execute functions since you have to find them everytime they are called.
The advantage is that you can be lazy about typing.
Typecasting primitaves are a whole other problem. I'm not even going to go into that, but check out scripting languages for examples of autocasting primitives.

Similar Messages

  • Why is my 1 type cast to value 0 enum?

    I've attached a VI that (for me, on my XP machine) typecasts my integer with value 1 to an enum with value 0.  I'm certain I've done this type of thing before with (what I believe) is the correct answer of the enum with value 1.
    Am I crazy to expect a different result?
       ...Dan
    Attachments:
    type_cast_crazy.vi ‏13 KB

    You can also change the type of the enum diagram constant to U32.
    Still, I agree with you that it should work as you expect and not as it currently does. A One is a One is a One... after all.
    It should not depend on the representation of the players. Am I missing something?
    LabVIEW Champion . Do more with less code and in less time .

  • Why we use type casting  ' ?='

    Hii Team
    sample code for fetching the input value from search view which is connected to btq1order contextnode
    DATA : lr_qs TYPE REF TO cl_crm_bol_dquery_service,
           lr_qr TYPE REF TO if_bol_bo_col,
    lr_qs ?= me->typed_context->btq1order->collection_wrapper->get_current( ).
    lr_qr = lr_qs->get_query_result( ).
    I am new to SAP CRM .while understanding the code i got stuck in one problem that ,
    1.what is the main purpose behind
    TYPE CASTING ie;  '?='
    2.what happens if we write ?=  becoz if we write  '='  instead of  '?='  the system thows an error.
    3.when to use this operator ?= and when we cannot use ?
    It is used almost every where in BOL coding .please help me  by giving complete explaination with an example if possible.
    Thanks in Advance

    Hi Abhishek,
    Please check returning parameter type for get_current_dquery() method. In case returning type is mutually convertible then you don't have to use type casting.
    But in case where you are taking results in some other type where results are compatible but with different structure then you use type casting.
    best example would be cl_crm_bol_entity and if_bol_bo_property_access. Here property access is an interface to class and hence we use type casting.
    Please refer to:
    type casting
    You can find more documentation on internet if you search for type casting.
    Regards,
    BJ

  • Dynamic [Runtime] type casting in Java

    Hello,
    This is my requirement.
    I have a method that takes class name as a parameter.
    Ex:
    Object myMethod(String classname){
    Object xyz = getObject(); //userdefine method which returns some object
    /*<b>I need to typecast above object with the class name passed as the method parameter</b>*/
    /*<b>How can i type cast this object</b>*/
    Object obj = (classname) xyz;
    return obj;
    In the above example, how can i dynamically typecast the object with class whose name is passed as the method parameter?

    Hello,
    This is my requirement.
    I have a method that takes class name as a parameter.
    Ex:
    Object myMethod(String classname){
    Object xyz = getObject(); //userdefine method which
    returns some object
    /*<b>I need to typecast above object with the class
    name passed as the method parameter</b>*/
    /*<b>How can i type cast this object</b>*/
    Object obj = (classname) xyz;
    return obj;
    In the above example, how can i dynamically typecast
    the object with class whose name is passed as the
    method parameter?Perhaps a little more background on the project (what you are trying to do) will help the experts here answer?
    /*with a class that takes a noarg constructor*/
    public Object getObject(String classname) throws Exception
      //might want to get a bit more specific with which exceptions it will throw
      return Class.forName(classname).newInstance();
    }Do I think this sometimes is indicative (perhaps even more often than not), of a possible design flaw? Yes..
    It gets a little trickier if you have constructors (you have to create a Class object representing the string with the .forName(..) ..and then use some reflection to determine constructors and then a bit of logic to determine which of those to use...)
    ~Dave

  • Two requirement type determined for PIR of a material

    Hi Experts,
    I have a scenario wherein for one of the material with stragety 50, when the PIR is getting transferred from one info structure to Demand Management (Version A0) i get two line items for the same demand in MD63. I.e one line item with requriement type VSE and another line item with requirement type VSFB. The transfer is through a custom program.
    What could be the reason for this? Why two requirement types are determined for the material? What is the determining factor?
    Thanks in advance for the response
    Best Regards,
    Ganesh

    You mean that the two line items in MD63 belongs to the different version ; active and inactive one? 
    Several things you can check.
    1  First check the MC7F whether configuration of your info structure is link to DM automatically (in Sync with Demand Management section).  If you create the transfer again, it may have duplicate records in demand management.
    2. Do you use the mass processing to transfer the data?  If so, please check the activity.  If you set the transfer twice, then it is duplicate.
    3.  Maybe someone maintained them manually and enter the requirement plan.  Normally the transfer from SIS will have blank requirement plan. Maybe you can check whether the requirement plan is maintained for any of the lines (in the item tab).  
    If you can do the screen shot for us, it will be very helpful to analyze.

  • USE OF Type cast function ?

    can any one explain the use of type cast function with help of example please i am not able to understand the explaination given in ni.com site

    LabVIEW provides a function called Type Cast, which allows data to pass through it unchanged while the type of the wire changes. Please refer to the given link which elaborates on the type cast function with required instances.
    http://zone.ni.com/reference/en-XX/help/371361H-01​/glang/type_cast/
    In case of any clarifications needed, do revert.
    Regards,
    Sahil Singla
    Applications Engineer | National Instruments
    (Give Kudos to good Answers and Mark it as a Solution if your problem is Solved)

  • Demand management - Requirement type

    Dear SAP Experts
    Could someone kindly explain to me  What  "Requirement type" ( eg.LSF , BSF) controls, and what settings do i have to make to use any each of them.
    How does each affect planning calculations?
    Thanking you all in advernce.
    Richard.

    Hi,
    Hope you would have gone through the SAP notes on Requirement Type which is reproduced as under
    Strategy for Determining the Requirements Type
    1. First, an attempt is made to find a requirements type using the strategy group in the material master.
    2. If the strategy group has not been maintained, the system will determine it using the MRP group.
    3. If the MRP group has not been defined, the system uses the material type instead of the MRP group when accessing the corresponding control tables.
    4. If no requirements type is found here, the system assumes a special rule and attempts to find a requirements type with the aid of the item category and the MRP type.
    5. If this is not possible, a last attempt is made to find a requirements type with the item category only.
    6. If the last attempt fails, the system declares the transaction as not relevant for the availability check or transfer of requirements.
    Now why we require it.
    becuase same requirement types can be assigned to any number of item cateogies for different MRP types. Since item cateogories cannot be assigned to requirement class directly, requirement type is a link between them.
    Though requirement type has no feature associated with it, it helps in assigning the correct requirement class in a sales document. Any number of requirement types can be assigned to requirement class. So MRP type in material master plays a vital role in fetching the rquirement class. Hence, you can enter manually the Requirement type in sale order but not Requirement Class.
    Thanks.......rakesh

  • Type cast exception

    Hi Guys,
    I am pretty new at generics and have started reading all material available online. Shown below is the API that I am using
    package api;
    public interface CS<C extends MyConfig> extends S {
    package api;
    public interface MyConfig {
    package api;
    public interface MySession {     
         public <C extends MyConfig, T extends ResourceContainer<? extends C>>
         T createContainer(CS<C> aPredefinedConfig);
    package api;
    public interface NC extends ResourceContainer<NCC>  {
    package api;
    public interface NCC extends MyConfig {
    package api;
    import java.io.Serializable;
    public interface ResourceContainer <T extends MyConfig> extends Serializable {
    package api;
    public interface S {
         public abstract boolean equals(Object other);
         public abstract int hashCode();
         public abstract String toString();
    }And below is my implementation
    package impl;
    import api.NC;
    public class NCImpl implements NC {
    package impl;
    import api.CS;
    import api.MyConfig;
    import api.MySession;
    import api.ResourceContainer;
    public class MySessionImpl implements MySession {
         public <C extends MyConfig, T extends ResourceContainer<? extends C>> T createContainer(
                   CS<C> predefinedConfig) {
              NCImpl ncimpl = new NCImpl();
              return ncimpl; //Error Type mismatch: cannot convert from NCImpl to T
    }As shown above I get error at line 'return ncimpl' But NCImpl implements the NC which extends ResourceContainer<NCC> so shouldn't it be capable of Type casting to T or I am missing something.
    Thanks a lot for your response in advance

    continuation of stack trace .................
    [INFO] ------------------------------------------------------------------------
    [ERROR] BUILD FAILURE
    [INFO] ------------------------------------------------------------------------
    [INFO] Compilation failure
    /home/abhayani/workarea/eclipse/workspace/workspace-2.x/GenericsTest/impl/src/main/java/impl/MySessionImpl.java:[16,13] inconvertible types
    found : impl.NCImpl
    required: T
    /home/abhayani/workarea/eclipse/workspace/workspace-2.x/GenericsTest/impl/src/main/java/impl/MySessionImpl.java:[16,13] inconvertible types
    found : impl.NCImpl
    required: T
    [INFO] ------------------------------------------------------------------------
    [INFO] Trace
    org.apache.maven.BuildFailureException: Compilation failure
    /home/abhayani/workarea/eclipse/workspace/workspace-2.x/GenericsTest/impl/src/main/java/impl/MySessionImpl.java:[16,13] inconvertible types
    found : impl.NCImpl
    required: T
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:579)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalWithLifecycle(DefaultLifecycleExecutor.java:499)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoal(DefaultLifecycleExecutor.java:478)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoalAndHandleFailures(DefaultLifecycleExecutor.java:330)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeTaskSegments(DefaultLifecycleExecutor.java:291)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.execute(DefaultLifecycleExecutor.java:142)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:336)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:129)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:287)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.codehaus.classworlds.Launcher.launchEnhanced(Launcher.java:315)
    at org.codehaus.classworlds.Launcher.launch(Launcher.java:255)
    at org.codehaus.classworlds.Launcher.mainWithExitCode(Launcher.java:430)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:375)
    Caused by: org.apache.maven.plugin.CompilationFailureException: Compilation failure
    /home/abhayani/workarea/eclipse/workspace/workspace-2.x/GenericsTest/impl/src/main/java/impl/MySessionImpl.java:[16,13] inconvertible types
    found : impl.NCImpl
    required: T
    at org.apache.maven.plugin.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:516)
    at org.apache.maven.plugin.CompilerMojo.execute(CompilerMojo.java:114)
    at org.apache.maven.plugin.DefaultPluginManager.executeMojo(DefaultPluginManager.java:451)
    at org.apache.maven.lifecycle.DefaultLifecycleExecutor.executeGoals(DefaultLifecycleExecutor.java:558)
    ... 16 more
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time: 5 seconds
    [INFO] Finished at: Thu Feb 12 10:39:43 IST 2009
    [INFO] Final Memory: 14M/81M
    [INFO] ------------------------------------------------------------------------
    [abhayani@localhost GenericsTest]$

  • Type casting

    In my program i get a double array from a function call, i want to convert this into an int array, but when i try to type cast it the compiler tells me they are inconvertible types. ie.
    int[][] mat = (int[][])mateng.getArray("arraySig");
    where the getArray function returns a double array.
    Is there any way around this? I have tried to cast the double[][] into an Object[][] array and then back to an int[][], but the compiler wouldnt let me do this either.
    Thanks
    Alex

    One might ask why you're returning a double[][] if you
    actually want a int[][]The method returns a double[][] because its a generic method that will also be used to get double[][]s. In those cases it wont do to lose the information that only returning an int[][] would lose.
    I wanted to be able to cast the double[][] to an int[][] when i return a specific matrix (ie a ones matrix or a logical matrix).
    Alex

  • Type casting of primitive types

    Hi,
    I have two pieces of code. The type casting between them is strange.
    1st snippet
    int i =100;
    byte b = i;This gives an precision error. where as this is allowed
    final int i =100;
    byte b = i;Pls explain as to why is this happening.
    Regards,
    Anand

    The compiler sees that the value is a constant, and that it can't change. And it can therefore validate that the value is within the valid range for a byte.
    /Kaj

  • Type Casting Exception

    I have an attribute CategoryId in my VO of type oracle.jbo.domain.Number. I am trying to use the expression of Boolean item in JHS as #{row.CategoryId != 4}
    Here is the generated JSF code:
                          <af:column id="s141NewItem3Col" noWrap="true" width="100"
                                     rowHeader="false">
                            <f:facet name="header">
                              <af:outputLabel value="CAtIDDeq4" showRequired="false"
                                              id="ol18"/>
                            </f:facet>
                            <af:inputText id="s141NewItem3"
                                          value="#{row.CategoryId != 4}"
                                          label="CAtIDDeq4" required="false"
                                          readOnly="#{((pageFlowScope.ContractRightCategoriesTable.newRow) and (!(jhsUserRoles['RM, ADMIN, AllButTitl, AllButAdmn']))) or ((!pageFlowScope.ContractRightCategoriesTable.newRow) and (!(jhsUserRoles['RM, ADMIN, AllButTitl, AllButAdmn'])))}"></af:inputText>
                          </af:column>I am getting the run time exception as "Can not convert 4 of type class oracle.jbo.domain.Number to class java.lang.Long"
    I am wondering how the row.CategoryId is treated as Long?. PLease advise. Also, will I be able to use type casting expressions in J Headstart/JSF Expression Language?
    Thanks, Pradeep

    I am trying to set disabled property of an item SubCategory dynamically based on CategoryId value. I guess the transient attribute will not work for newly created records as the transient attribute will be null for newly created records before save is performed. However, the expression #{row.bindings.CategoryId.attributeValue.value== 4 ? false : true} is working fine. row.bindings.CategoryId.attributeValue seem to be returning Long and, row.bindings.CategoryId.attributeValue.value might be returning a Number.

  • TYPE CASTING ERROR

    HI GURU's
    I AM REQUIRED TO GENERATE USER ID AUTOMATICALLY STARTING FROM 0001, 0002, 0003 AND GOES ON INCREMENTING BY 1.
    - I MADE USER ID FIELD OPTIONAL.
    - THEN I CREATED AN ENTITY ADAPTER TO TRIGGER AT PRE INSERT EVENT, TAKING INITIAL VALUE AS 0000 IN A INTEGER VARIABLE.
    - THEN OTHER VARIABLE STORES THE INCREMENTED VALUE OF INITIAL VALUE (INT ADD METHOD).
    - THEN I MAPPED THE ADAPTER RETURN VARIABLE WITH THE ENTITY VALUE USER ID OF USER FORM.
    WHEN I TRY TO CREATE USER IT SAY ERROR IN TYPE CASTING, OBVIOUSLY IT SHOULD SHOW BECAUSE I AM MAPPING INTEGER RETURN VARIABLE WITH THE STRING TYPE USER ID.
    KINDLY SHOW ME THE WAY TO ACHIEVE THIS.
    THANKS A LOT.

    Have you tried searching this on Google.
    See this link:
    http://www.javadb.com/convert-an-int-value-to-string
    In your Entity Adapter code, write few more lines from the method in the above link.
    THEN I CREATED AN ENTITY ADAPTER TO TRIGGER AT PRE INSERT EVENT, TAKING INITIAL VALUE AS 0000 IN A INTEGER VARIABLE.
    - THEN OTHER VARIABLE STORES THE INCREMENTED VALUE OF INITIAL VALUE (INT ADD METHOD).
    - THEN I MAPPED THE ADAPTER RETURN VARIABLE WITH THE ENTITY VALUE USER ID OF USER FORM.

  • How to use Type Casting in JSF Expression Language

    I have an attribute CategoryId in my VO of type oracle.jbo.domain.Number. I am trying to use the expression of Boolean item in JSF as #{row.CategoryId != 4}
    Here is the JSF code:
                          <af:column id="s141NewItem3Col" noWrap="true" width="100"
                                     rowHeader="false">
                            <f:facet name="header">
                              <af:outputLabel value="CAtIDDeq4" showRequired="false"
                                              id="ol18"/>
                            </f:facet>
                            <af:inputText id="s141NewItem3"
                                          value="#{row.CategoryId != 4}"
                                          label="CAtIDDeq4" required="false"
                                          readOnly="#{((pageFlowScope.ContractRightCategoriesTable.newRow) and (!(jhsUserRoles['RM, ADMIN, AllButTitl, AllButAdmn']))) or ((!pageFlowScope.ContractRightCategoriesTable.newRow) and (!(jhsUserRoles['RM, ADMIN, AllButTitl, AllButAdmn'])))}"></af:inputText>
                          </af:column>I am getting the run time exception as "Can not convert 4 of type class oracle.jbo.domain.Number to class java.lang.Long".
    I am wondering how the row.CategoryId is treated as Long?. PLease advise. Also, will I be able to use type casting expressions in JSF Expression Language?
    Thanks, Pradeep

    use attributeValue
    Try *#{row.bindings.CategoryId.attributeValue != 4}* ?
    Check this thread for details which discusses about the same:
    El expression to disable  or enable
    Thanks,
    Navaneeth

  • Type casting in generics 2

    Is there any way to avoid casting in following code using generics.
    public Interface SomeInterface
    public class SomeClass implements SomeInterface
    public class SomeClass1
    public void meth(SomeInterface obj)
    SomeClass cls = (SomeClass) obj;
    }

    why would you want to cast the interface to the concrete class? if SomeClass implements SomeInterface, presumably it's because what your client code is interested in is SomeInterface, that's why we use interfaces. you can't be sure that obj is always going to be an instance of SomeClass, only that it's an instance of SomeInterface. If you could be sure, there'd be no point having the two types
    generics are a non-issue here

  • Type casting in Java

    Hi,
    Can we do explicit type casting vigorously in a java class? Im in a situation that i've to do explicit casting 40 to 50 times in a class. Is there any overhead for JVM or any performance issue with this?

    Why do you cast so often? It's sounds like a weird design. Casting is pretty cheap.
    Kaj

Maybe you are looking for