RTTI vs Compiler Type Identification (Casting?)

Given:
Class Super and two subclasses of Super, SubOne and SubTwo.
Super has one method, doBeDooBeDoo()
SubOne has one method, doThis()
SubTwo has one method, doThat()
Super a = null;
if(foo) {
    a = new SubOne();
    a.doThis();
} else if(bar) {
    a = new SubTwo();
    a.doThat();
a.doBeeDoBeeDo();When I attempt to compile code like this, I receive a compiler error message indicating that class Super does not have a doThis method or a doThat method.
Conversely, when I run the following code...
Super a = null;
a = new SubOne();
System.out.println(a.getClass().getName());
a = new SubTwo();
System.out.println(a.getClass().getName());... I obtain the desired output of 'SubOne.class' and 'SubTwo.class'.
My confusion stems from the fact that when a = new SubOne() fires, object 'a' is an instance of SubOne, not an instance of Super. It appears that the compiler isn't picking up on this fact (understandable, since it only happens at runtime).
My questions:
1) Am I understanding the problem correctly or am I off-track?
1a) Am I misunderstanding the rules of casting in thinking that I can declare an object as being of one type and then instantiate it as a subtype?
2) Is there a way to force the compiler to recognize the casting that takes place when Super s = new SubOne()?

Thank you both for your replies - that helps to clear
up some of my confusion. I settled with...
Super a = null;
if(foo) {
a = new SubOne();
SubOne sub = (SubOne)a;
sub.doThis();
} else if(bar) {
a = new SubTwo();
SubTwo sub = (SubTwo)a;
sub.doThat();
a.doBeeDoBeeDo();...which seems equivalent to guifrei's response, but
somewhat more concise when the subclasses have a
number of unique methods.what is the point of having variable a in type of superclass, if you are not using it?
notiece that you are defining instances of your own subclass...
instead of a = new SubTwo();SubTwo sub = (SubTwo);sub.doThat(); you would most likely like to use the one with casting...
there is no point to assign value to a if you will end up using sub instead?!
ok, there is that a.doobidoobido fing outside if's... that maybe...
well.. actually i ment to write also about overloading your doBiDooBiDoo() method.
if you have in SubOne and SubTwo methods that do different thing, but have the same name as their superclass, then you can call a.doBiDooBiDoo() outside if and else-if and the result will depend on values of foo and bar.
and notiece that if you have line:
super a = null;
before these if statements, then in case foo and bar are false, you'll get nullpointerexception because a had no value...
so consider valuateing a with not-null value (super a = super();)
i hope i got some ideas from that, allthough i lost my point somewhere right before i started typing this...

Similar Messages

  • Java RTTI - Run type type identification

    This Question might seem odd; but its true:
    In Java we have getClass() for an Object to know its REAL TYPE. But we dont have any method to get its CASTED TYPE class. Although, throughout code we know it at coding time; there might be cases where we want to know it programatically; (for creating inheritance relationships on the fly.)

    I don't know why you would ever need this unless you were writing a compiler. If you keep a reference to an object, that reference is whatever the casted type is. i.e. void foo( MySubclass inSub, MySuperclass inSup )
        MySuperClass mySup = inSub; // can be done implicitly
        MySubClass mySub = (MySubClass)inSup; // legal, but can throw a ClassCastException
    }and anywhere later in foo() the casted class is already known.
    You might be able to use reflection to do more dynamic casts, but you still aren't going to keep a different reference....
    I think maybe what you want in this case is something more like an interface where you know specific methods need to exist and you can override them...

  • I need clarification regarding REFERENCE TYPES and CASTING.

    Hello all,
    I'm taking a course on the fundamental of JAVA. Everything's been going smoothly until I slammed into the the concept of CASTING and REFERENCE TYPES. Flat--out == I DON'T GET IT?
    I'm having trouble with...
    CONVERTING REFERENCE TYPES
    CASTING BETWEEN REFERENCE TYPES
    WORKING WITH REFERENCE TYPES
    I understand what's happening from an academic vantage point. I just don't understand why you'd want to convert REFERENCE TYPES? What would be an application of such an exercise?
    1. What IS a REFERENCE TYPE -- exactly?
    a. what are we referencing?
    b. type? type of what??
    for example... why would you want to do a widening conversion, a conversion of the hierarchy tree?
    I understand the concept of OBJECTS, CLASSES, METHODS and CONSTRUCTORS so far...
    I think it's the terminology that's screwing my up.
    Thanks,
    Alex

    ok... wow, thanks J.
    So--in a nutshell-- we're making it so that different
    objects:
    ie,. ford(), chevy(), honda(), lotus() and
    dealers()... so and so forth()...
    all share the resources(for lack of a better word) of
    the Auto Class? because all of those auto brand
    objects and one redically different object can be
    unrelated, correct?Um, yes and no.
    I just ran with the example you had, but that probably included too many concepts and they got muddied up.
    Yes, Chevy, Ford etc. all share the characteristics of Auto, since they're all subclasses. But that's just inheritance, and has nothing to do with casting.
    A "reference type" can loosely be described as a variable that refers to an object. (Constrasted with "primitive types" which are int, char, float, etc. and don't refer to objects--they just hold values.)
    Casting just tells the compiler that even though as far as it knows you only have a reference to some superclass, the object that reference points to will in fact be an instance of a subclass, and so treat it as such (e.g., we can now call methods that the subclass has that the superclass lacks).
    (You can also cast primitives, but one thing at a time.)
    So let's say you have class A (which extends object) and B extends A.
    A a = new B();
    B b = a; // won't compile. compiler sees the "A a" on the left of the =, not "new B()" on the right.
    B b = (B)a; // works because we're telling the compiler, "Dude, I'm seriously. This is a B.
    Note that if we had done new A() instead of new B(), it would still compile--the compiler would trust us. But at runtime, we'd get a ClassCastException, since we wouldn't actually have a B object.
    /**folks, I'm a web designer that has to learn Java
    so that I can perform my duties as a JSP author here
    at work. I tried to learn JSP sans Java and that was
    a simple exercise in ignorance.-- it's really hard
    without understanding the root concepts of Java and
    for that matter, C. Concepts like "polymorphism,
    inheritance, object references... are completely
    foreign to me. **/It's a rather big leap from web designing to OO concepts. Take your time, and don't be discouraged if you feel completely confused. It's a prerequisite. :-)

  • Java Types Conversting & Casting .

    Hi All !
    Really i do have two questions regarding Java Type Conversion and Casting
    and hope i would find (good) answers :
    [Q1:]
    why it's legal to convert(implicitly) from ( long --> float ) and this is
    said to be a widening conversion even if the size of long is longer than float
    and hence there a possible loss of information ?
    [Q2:]
    why it's legal to cast(explicitly) from ( byte --> char ) and how compiler will deal
    with byte as singed and char as unsigned during type casting (this is said to be
    a narrowing converstion and it is really is ) ?
    for [Q2:] i did the follwing code :
    public class TestNarw
         public TestNarw()
              byte bBefore=-100; // change this value to whatever negative number that is to fit in a byte.
              char c=(char)bBefore;
              byte bAfter=(byte)c;
              System.out.println(bBefore);
              System.out.println(c);
              System.out.println(bAfter);
         public static void main(String args[])
              new TestNarw();
               the SURPRISE on the code above is that the output is :
    -100
    -100
    and when i change the value of "bBefore" to any negative number that is to fit in a
    byte it (e.g: -10) it gives the same value for the variable "c" (character)which is ASCII "63" ="?"
    but when i test it with a suitable postive number , it works fine and the character (c) represents that number
    so how it deals with converstion from negative byte to char ?
    Thanks ...

    Q1: you can always cast between primitive types (numbers, not boolean). The only problem is you lose precision in certain directions. A long to float isn't necessarily going to change the value, but it really depends on the long value. If it's out of range of float, it'll basically be wrapped around to the negative side. (at least that's what long to int would do, not sure if float or double behave different in that regard).
    Q2: The value -100 converted to a char would probably be 65436, which prints as "?" because DOS can't print that character. Then when you cast back, 65436 is out of range for a byte, so it rolls back around to -100.
    Try this:
    byte b = 127;
    System.out.println(b);
    System.out.println((byte)b+1);
    System.out.println((byte)0xFF); // 255 in hex
    It'll print 127, then -128, then -1. When you go out of range, it just wraps around. For this reason, you often have to be carefull what size you store things as.

  • How do you compile "type body" objects that are invalid?

    We just completed a few application upgrades and now the objects catindexmethods and textindexmethods are invalid. These are part of our intermedia install but haven't started using it yet. How to I recompile these objects to be valid again?

    Did a little deeper and you shall find it:
    alter type xxx compile body;

  • Cannot compile TYPE  ORA-02311

    Hi,
    I have some similar TYPE's in DB one TYPE is VALID, but all other is invalid and i cant compile- Error [1]: ORA-02311: cannot alter with COMPILE option a valid type with type or table dependents
    Any sugestions ?
    THANKS!
    ID.

    Hi,
    if I execute your statements also in mine I have 2 objects:
      SELECT object_name, subobject_name, object_type, status
           , last_ddl_time
        FROM all_objects
       WHERE object_name = 'MOVEMENT_T'
    ORDER BY last_ddl_time;
    OBJECT_NAME                    SUBOBJECT_NAME                 OBJECT_TYPE         STATUS  LAST_DDL_TIME
    MOVEMENT_T                     $VSN_1                         TYPE                VALID   02-JUL-13  
    MOVEMENT_T                                                    TYPE                VALID   02-JUL-13  
    It looks that when you alter the TYPE another line is shown in all_objects.
    It is also possible that the ALTER statement did not finish correctly.
    You can have a look here: Advanced Topics for Oracle Objects
    Check chapter
    Altering a Type by Adding and Dropping Attributes
    Regards.
    Al

  • Using RTTI in table type any

    Hello,
    i have table type any and i want to know in the loop for every field which type he have ,for instance for field type Date8.
    what i the best way to do so , i guess that I need to use for instance cl_abap_elemdescr=>get_data_type_kind( <lv_field> ) but i dont know
    how to use it and check every field in the loop ...
    E.g.
    loop at <lt_fields> assigning <ls_fields>
    * check for every field in <ls_fields> which type he have and if the field is type date8
    * handle it diffrently
    endloop.
    Regards
    Joy

    You can use Absolute Name to get the absolute type from the type descriptor.
    DATA: lt_vbak TYPE STANDARD TABLE OF vbak.
    DATA: lo_struct   TYPE REF TO cl_abap_structdescr,
          lt_comp     TYPE cl_abap_structdescr=>component_table,
          la_comp     LIKE LINE OF lt_comp.
    lo_struct ?= cl_abap_typedescr=>describe_by_name( 'VBAK' ).
    lt_comp  = lo_struct->get_components( ).
    WRITE: /(30) 'Field' , (40) 'Absolute Type'.
    DATA: lv_abs_name TYPE string.
    LOOP AT lt_comp INTO la_comp.
      WRITE: /(30) la_comp-name, (40) la_comp-type->absolute_name.
    ENDLOOP.
    Regards,
    Naimesh Patel

  • Run-Time Type Identification question

    Let's say I have a class Chart and 2 subclasses BarChart. and LineChart. I have a method that takes in the type of chart to create as a parameter and then creates the appropriate chart. Something like:
    public void createChart(int type){
    Chart ch = ChartFactory.getChart(type); //type could be Chart.LINE or Chart.BAR
    //Line x
    Now, at Line x above, if I want to call a method that is specific to BarChart such as getBarWidth(), how would I go about it?
    Thanks.

    You're only going to call getBarWidth() in a context that knows it's dealing with a BarChart. The question is how to get your design in such a form so it doesn't have to say "If this is a BarChart then call getBarWidth()". I don't exactly know how you would do that but I suggest it should be your desire to do that.
    Let me give a crude example that may or may not have anything to do with your project.
    You display a chart and you want to give the user a panel of controls so they can tinker with the way it looks. Controls like the width of the bars in a bar chart, whether or not one of the pieces is offset from the others in a pie chart, the dottedness of the line in a line chart, and so on.
    In this case the factory should have a method that takes a chart type (or maybe a chart) and returns a panel of suitable controls. This panel will have only the controls that are suitable for that chart type, and it will be given a reference to a chart that it assumes is of that type.
    And similarly. Each time you feel like using instanceof, go back and see if you can't get the factory to do the work.

  • Bin type identification

    Hi,
    If I have below information
    Row             Column                Level            Euro Pallet               Industrial Pallet             Height of the bin
    01                  01                        01                    4                               0                                     100 CM
    01                  01                        02                    4                               2                                     100 CM
    01                  01                        03                    4                               2                                     150 CM
    how many Bin type I need to create as in 1 st level I cant keep industiral pallet, on 2nd & 3rd level I can keep same number of pallets but it has different height.
    How many bin type I need to create. As storage type for all three level is same how can I control that for  the industrial pallet should not suggest 1st level in the transfer order 

    Based on the height of the bin you need to create the bin type (e.g.
    Height of the bin              EP        IP
    100 CM -- B1                     Y            N
    100 CM -- B2                     Y            Y
    150 CM -- B3                     Y            Y
    Assignment storage unit type to Storage type (Assume your storage type is ST1  & Storage unit type is EP & IP)
       ST1  --- IP,EP(maintain value of all the storage unit type which can be stored in that bin)
    Storage unit type to storage bin type assignment this will take care that IP is not going to 1st level
    EP ----B1,B2,B3
    IP -----B2,B3

  • SPML request type identification

    I have a need to be able to identify which type of request I received while still in the SPML form. Anyone know of a variable or attribute that may be of any assistance to me? The "<spml:addRequest" is right there at the beginning of the request. I just can't figure out how to get at it.
    Thanks -T-

    Even we have the same requirement. Have you been able to capture the request type?

  • Field Name  of the field on the Selectiion Screen

    Hi,
    I am executing report program and we get a Selection Screen .The question is  can we catch the field names of the fields on the selection screen dynamically.
    We can find the field name by pressing F1 and looking into the Technical Information of that perticular field.
    But can we fetch the field name dynamically.
    Any pointers/information in this regard will be highly helpful.
    Thanks & regards,
    Abhijeet

    Hello Abhijeet,
    Here's what I think you're looking for -
    tables spfli.
    parameters     : p_test   like spfli-carrid.
    select-options : s_carrid for  spfli-connid.
    DATA:
      descr_ref TYPE ref to cl_abap_elemdescr.
    START-OF-SELECTION.
      descr_ref ?= cl_abap_typedescr=>describe_by_data( p_test ).
      WRITE: / 'Typename     :', descr_ref->absolute_name.
      WRITE: / 'Kind         :', descr_ref->type_kind.
      WRITE: / 'Length       :', descr_ref->length.
      WRITE: / 'Decimals     :', descr_ref->decimals.
      WRITE: / 'Output Length:', descr_ref->output_length.
      WRITE: / 'Help ID      :', descr_ref->help_id.
    Kind------> data type (C , I , etc.,)
    Help ID---> data element (usually).
    There are other classes in ABAP of the form CLABAPDESCR which can provide you with other information. These classes all belong to what is called RTTI (Run Time Type Identification). However, these are available only from 46c. You can explore the other classes, as I think they would be very interesting and useful in the future.
    Regards,
    Anand Mandalika.

  • Class.GetName or .InstanceOf(className) in ABAP

    Dear all,
    how do you realize the java methods/checks
    class.GetName or
    (Is)InstanceOf(className)
    of a current class instance in ABAP OO ?
    best regards,
    Christoph Aschauer

    Hi Christoph
    Will it be useful to use <b>RTTI (Run-Time Type Identification)</b>? That is, the class <b>"CL_ABAP_TYPEDESCR"</b> and its subclasses. One of its subclasses (<b>cl_abap_classdescr</b> as I remember) can be used to identify the type of an instantiated object.
    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>

  • Find screen by name

    I want to write a method that find screen by name: however it
    seems that screen doesn't have a property or method that returns
    its instance name...
    in the following code:
    for(var i=0;i<root.numChildScreens;i++){
    var cat=root.getChildScreen(i);
    trace(cat.instanceName); //undefined
    trace(cat.label); //undefined
    trace(cat.name);//undefined
    trace(cat); //valid
    I know how to reference a screen by just doing
    parentScreen.childInstanceName, by I want to do it dynamically,
    hence the reason for the code above.
    please help!
    thanks!

    Hello Abhijeet,
    Here's what I think you're looking for -
    tables spfli.
    parameters     : p_test   like spfli-carrid.
    select-options : s_carrid for  spfli-connid.
    DATA:
      descr_ref TYPE ref to cl_abap_elemdescr.
    START-OF-SELECTION.
      descr_ref ?= cl_abap_typedescr=>describe_by_data( p_test ).
      WRITE: / 'Typename     :', descr_ref->absolute_name.
      WRITE: / 'Kind         :', descr_ref->type_kind.
      WRITE: / 'Length       :', descr_ref->length.
      WRITE: / 'Decimals     :', descr_ref->decimals.
      WRITE: / 'Output Length:', descr_ref->output_length.
      WRITE: / 'Help ID      :', descr_ref->help_id.
    Kind------> data type (C , I , etc.,)
    Help ID---> data element (usually).
    There are other classes in ABAP of the form CLABAPDESCR which can provide you with other information. These classes all belong to what is called RTTI (Run Time Type Identification). However, these are available only from 46c. You can explore the other classes, as I think they would be very interesting and useful in the future.
    Regards,
    Anand Mandalika.

  • Casting primitive wrap type variable to primitive

    We have this code:
    float f = 22.2f;
    System.out.println((int)f);
    Which prints out "22".
    Float f = 22.2f;
    System.out.println((int)f);
    When i changed the variabile type from float to Float, code throw up a compile a error, that Float type cannot be casted to int. Can somebody tell me what's going on? Isnt compiler supposed to do unboxing the variable to primitive float and then primitive float to be casted to an int?
    System.out.println((int)f.floatValue());
    Isnt that what the compiler is supposed to do? Code which works perfectly fine.
    Thank for your help.

    Hello vcraescu,
    I think you are wondering why the compiler does not convert from Float to float (unboxing) and subsequently from float to short (your cast), so the bug report probably does not help you too much.
    Casts come into play when the compiler can not assure that the statement is semantically correct. The bytecode would be the same with or without the cast (if the compiler would accept omitting casts).
    Casting primitives:
    int i = 0;
    short s = (short)i;Purpose of the cast: The compiler has no idea whether the two higher bytes are relevant and you therefore need to specify that they are not.
    Casting reference types:
    With reference types there are two types of casts, the upcast and the downcast.
    class Exampe {
         public static void example(Object... objects) {
              for (Object object : objects) {
                   System.out.print(object);
                   System.out.print(' ');
              System.out.println();
         public static void main(String[] args) {
              Object[] objects = { "String", 123, 1.23 };
              example(objects);
              example((Object) objects);
    }The purpose of this (up)cast is that you want the object to be treated as beeing of a more general type.
    org.w3c.dom.Node node;
    switch(node.getNodeType()) {
         case org.w3c.dom.Node.ELEMENT_NODE:
              org.w3c.dom.Element element = (org.w3c.dom.Element) node;
         case org.w3c.dom.Node.TEXT_NODE:
              org.w3c.dom.Text element = (org.w3c.dom.Text) node;
         default:
    }These casts tell the compiler that you are certain the object node is of a more specific type.
    My point is that all these casts have a distinct purpose. Your cast on the other hand does not. Looking at your code I see a conversion from a wrapper to a primitive, not necessarily the loss of precision connected with it and that is what this cast should be about.
    With kind regards
    Ben Schulz

  • Use cast('12345' as tab.col%type) as a substr - PLS-00220

    Hello,
    I like to make sure that my constructed string fits into my variable, in a flexible way.
    The variable is like
    declare  t_comment tab.col%type; -- tab.col%type = varchar2(4)
    and in the PLSQL I would like to do concat a string and make sure it fits in my variable, just cut the right end if it is too long. I want it to be dynamic, so NOT
    t_comment := substr('1234567', 1, 4)
    CAST () works like a substring operator if casting to a smaller data type, but also leads to hardcoding.
    t_comment := cast ('1234567' as varchar2(4))
    But I want
    t_comment := cast ('1234567' as tab.col%type)
    But that gives me a
    PLS-00220: simple name required in this context.
    And when I define a subtype
    subtype comment_type is tab.col%type;
    t_comment := cast ('1234567' as comment_type)
    gives me a 
    PLS-00382: expression is of wrong type
    The documentation is also clear:
    CAST converts one built-in datatype or collection-typed value into another built-in datatype or collection-typed value.
    But it would be so nice to prevent hardcoding, to the varchar2(4) datatype in this case.
    Any suggestions on how to make this flexible?

    Hello,
    you can read the column length from the data dictionary and then use it in your SUBSTR instead of the hard coded value:
    SELECT data_length
    INTO v_length
    FROM user_tab_cols
    WHERE table_name = 'TAB'
    AND column_name = 'COL';
    t_comment := SUBSTR('1234567', 1, v_length);
    Not as simple as a %TYPE, but just as flexible.
    Regards
    Marcus

Maybe you are looking for

  • How to save jpeg files in iPhoto

    I would like to be able to make changes in Photoshop and then be able quickly save a jpeg file in my iPhoto library (Version 9). From what I could deduce, the only way to do this would be to save the file to my hardrive, then go to iPhoto, choose the

  • Problem with Multicolumn Listbox Scrolling

    Hello... Can anybody please tell me how to scroll according to row no. in multicolumn listbox?                 I'm working on a VI where I have to test some conditions which are depending upon RPMs... For testing ease I have sorted the conditions acc

  • Adobe Pro 9 installation

    I'm looking for information on how to make a network unattended install of Adobe Pro 9. To be more clear I want to: Have Adobe 9 setup files on a server share and be able to let people click the setup.exe or adobe .msi file and it run fully or mostly

  • Help with dynamic NAT and CSM 4.4 and ASA 8.3

    Hello I currently try to add a dynamic NAT rule into CSM 4.4 for a ASA 8.3 device, but I fails at the deployment with the error message: Failed to generate delta config The following commands have not been recognized by the Configuration Parser: ====

  • Stale connection kills the VM

    Here is the scoop: a process (JDK 1.3 w/ Oracle OCI driver v8.1.6, running on Windows 2000) establishes a connection to the database (Oracle 7.3.4) and opens a number of PreparedStatement(s). While the connection is open and idle, the database instan