" casting in java "

Hi All,
Can some one help me find out whats the error in my code??
what/where is wrong in my casting??
import java.lang.* ;
class base {
public void display()
System.out.println( " i am in base ");
class derv extends base{
public void show()
System.out.println( " i am in derv ");
class test13 {
public static void main(String args[]) throws ClassCastException {
base Obj1 = new base();
base Obj2 = new derv();
derv Obj3 = new derv();
//derv Obj4 = new base();//not valid
Obj1.display();// regular
Obj2.display();
Obj3.display();
Obj3.show();// regular
derv Obj4 = new derv();
Obj4 = (derv) Obj1;
Obj4.show();
derv Obj5 = new derv();
Obj5 = (derv) Obj2;
Obj5.show();
};i am getting a run time exception like this :
C:\JAVAEX~1\test>java test13
i am in base
i am in base
i am in base
i am in derv
Exception in thread "main" java.lang.ClassCastException: base
at test13.main(test13.java:37)
Thank you very much in advance..
Thanks and regards,

The cast cast occured because you tried an downcast.
may be this could help
public class A1{
     A1(){
          A1 a=new A1();
          B1 b=new B1();
          //up cast...
          A1 a1=b;// no need of explisit cast
          //down cast          
           /*explisit cast requires..may throw exception, if a is not an instance of B1..
          ie. it will thorow excpetion in this case*/
          B1 b1=(B1)a;
          //example of not throwing excpetion..
          B1 b2=(B1)a1;
class B1 extends A1{

Similar Messages

  • Getting Error:::oracle.jbo.domain.Date cannot be cast to java.lang.String

    Hi Friends,
    I have simple req'.
    i have one date filed in OAF page...if user has change the date filed..means if he incresed by 2 days..then i need to call one procedure..if not no need to call....
    first am picking that date field to by uusing prepared stmt and putting in to one variable..like below
    try {
    ps1 = am.getOADBTransaction().getJdbcConnection().prepareStatement("SELECT -------");
    ResultSet rs2 = ps1.executeQuery();
    while (rs2.next()) {
    schDate = rs2.getString(1);//storing the value
    } catch (Exception e) {
    throw OAException.wrapperException(e);
    Next..am picking the current value like this(user can change the value) like below...
    OAViewObject viewObj = (OAViewObject)am.findViewObject("simpleVO");
    String currSchDate = (String)viewObj.getCurrentRow().getAttribute("iDate");
    java.text.SimpleDateFormat dtFormat = new java.text.SimpleDateFormat ("MM/dd/yyyy");
    StringBuilder date = new StringBuilder(dtFormat.format(currSchDate));
    Then am comparing the values like below..
    if (schDate.equals(date)) {
    String outParamValue = "";
    String secondOutParamValue = "";
    but am geting the below error
    ## Detail 0 ##
    java.lang.ClassCastException: oracle.jbo.domain.Date cannot be cast to java.lang.String
         at xxuss.oracle.apps.abc.webui.xxPGCO15.processFormRequest(xxGCO15.java:594)
    Appriciate any help...its very urgent
    Regards
    Harry

    Instead of :
    String currSchDate = (String)viewObj.getCurrentRow().getAttribute("iDate");Try
    String currSchDate = viewObj.getCurrentRow().getAttribute("iDate").toString();
    -Anand

  • Java 7 update 51 cause the following error: java.util.HashMap cannot be cast to java.awt.RenderingHints

    Since I installed Java 7 update 51 accessing the EMC VNX Unisphere Console cause the following error: java.util.HashMap cannot be cast to java.awt.RenderingHints.
    I rolled back to Apple Java 1.6 -005 now I am getting the following error: plug-in failure.
    I think this is cused by the fact that the EMC console application has been written for java 7 and not java 6. Has anybody faced and solved the "java.util.HashMap cannot be cast to java.awt.RenderingHints." error ?

    Hi Yaakov,
    The error is thrown from the  eclipselink.jar:2.5.1 which is a JPA provider .
    Is the above jar bundled in the Oracle Product you are working upon or was this downloaded from external site ?
    If the jar is bundled with the Oracle Product, go ahead a log a SR with Oracle Support with Toplink product group to drill down on the issue, as the issue is happening internally or thrown by the Eclipselink implementation and we've no control....
    Hope it helps!!
    Thanks,
    Vijaya

  • Get / Cast a Java Object

    Does anybody know how to get (or Cast) a Java Object returned from a Java method call ?
    Example:
    <cfset someList = object1.method1(someString, JavaCast("float",someNumber),...)>
    This method returns a list of Java object of type "Object2". ie. it returns List<Object2>
    Now I attempted to loop thru each objects from the returned list, and invoke some method on them, using code similar to below,
    <cfset var="#someList[index]#"/>
    but ColdFusion does not seem to understand the object "var" as Java "Object2". Is there any way I can cast the "var" to "Object2"?
    Thanks in advance.
    Xiaoling

    "var" is a reserved keyword! You can initialize variables with "var" in the beginning of a component, but do not use it as a variables name:
    <cfset var someVar = "#someList[index]#">

  • Weblogic 10.3 error apache ListOrderedMap cannot be cast to java HashMap.

    Hi All,
    I'm having following code which is using spring(version: 2.0) dao
    public Map<String, String> getEmplyeeMap() throws Exception {     
              StringBuffer query = new StringBuffer("");
              query.append("select emp_name,dept_name from EMPLOYEE order by emp_no");
              logger.info("Inside getEmplyeeMap...Query to be executed :"+query.toString());     
              Map<String, String> EmpMap = new LinkedHashMap<String, String>();
              List<Map<String,String>> l_lstQueryRes = (ArrayList<Map<String,String>>)getJdbcTemplate().queryForList(query.toString());
              logger.info("l_lstQueryRes:"+l_lstQueryRes);
              if (l_lstQueryRes != null)
                   for (int l_iLoop = 0; l_iLoop < l_lstQueryRes.size(); l_iLoop++)
                        Map<String,String> l_mapRowData = new HashMap<String,String>();
                        l_mapRowData = (HashMap<String,String>)l_lstQueryRes.get(l_iLoop);                    
                        EmpMap.put(l_mapRowData.get("emp_name"), l_mapRowData.get("dept_name"));
                   }//End of for loop
              }//End of if loop          
              logger.info("EmpMap list size is.." + EmpMap.size());
              return EmpMap;
         } //End of getEmplyeeMap
    getting below error
    org.apache.commons.collections.map.ListOrderedMap cannot be cast to java.util.HashMap
    I'm thinking this problem is occurring because of jdk1.6 version, is anyone come across this problem?? This same working good in weblogic9.2 version.
    Thanks advance.
    Regards,
    Sharath.

    user9222505 wrote:
    Ok, thanks. So how do i determine where we are at since I have this "465"? How does that relate to a particular patch?
    Logger@9214443 3.5.3/465I believe, you are on 3.5.3 unpatched, and if I correctly remember, after applying the 3.5.3 patch 4 it should like like 3.5.3p4/... or 3.5.3.4/... (don't remember which one)... You would have to download that patch from your Oracle Support website (whichever you use), and apply the patch to a pristine extracted directory of 3.5.3 according to instructions in the patch zip.
    Starting with a recent version no more manual patching is necessary and you can download full distributions of patched versions from Oracle Support, but I don't think that applies to 3.5.3, yet (although it is possible that they recreated patch artifacts like that for earlir versions).
    If you do not have a support contract then you cannot download a patch or patched versions. You can only download a new full release which always has any previously released patches incorporated, though 3.5.3 is the last 3.5 full release if I correctly remember... and 3.6 comes with code incompatibilities at a few places so it is not a drop-in replacement...
    Best regards,
    Robert

  • How to resolve oracle.jbo.Key cannot be cast to java.util.List?

    Hi experts,
    I am getting this error (oracle.jbo.Key cannot be cast to java.util.List) PPR# . . . . . while filtering in grid..
    give some idea to solve this please...
    Note: (This error is occurs only in JDev ver 11.1.1.3.0 and its working fine in 11.1.1.2.0)
    Regards,
    Gops

    I guess information is too less, could you provide some more info ?
    Amit

  • Could not type cast in java embedding

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    org.xml.sax.InputSource in = (org.xml.sax.InputSource) getVariableData("Invoke_1_getRoutingAndFrameJumpers_OutputVariable","getRoutingAndFrameJumpersResponse");
    Document doc = db.parse(in);
    In the above code I am trying to type cast the variable getRoutingAndFrameJumpersResponse into org.xml.sax.InputSource so that i can parse.
    I am not getting any error during compilation
    but I am unable to type cast some run time error is coming in the line were I am type casting but I am not able to see the runtime error.
    How can I see the runtime error in java embedding, how to type cast a variable into xml so that I can parse it.

    Hi Arun,
    Could you try using the bpelx:rename extension in an assign activity enables a BPEL process to rename an element through use of XSD type casting.
    <bpel:assign>
    <bpelx:rename elementTo="QName1"? typeCastTo="QName2"?>
    <bpelx:target variable="ncname" part="ncname"? query="xpath_str" />
    </bpelx:rename>
    </bpel:assign>
    Cheers
    A

  • Any way to search for casts in java source code?

    Anyone know of a decent way to search your java source files to find all the casts?
    I ended up doing a simple text search for
         " = ("(quote marks not included) which works for my code because I am strict about writing my casts with spaces like
         String s = (String) iterator.next();Unfortunately, the above search has all kinds of problems with both false positives and negatives. It picks up lots of irrelevant lines like
         int index = (number > 0) ? 0 : 1;as well as misses casts that appear nested inside expressions like
         ((String) iter.next()).charAt(...)I suppose that one could do a regular expression search for any pair of open and close parens which bound non-blank text, but that would pick up even more non-cast expressions in typical java code.
    I think that the only way to properly do this is to have a tool which understands java syntax.
    Anyone know of an IDE which will do this? Does IntelliJ or Netbeans support this kind of search?
    In case you are wondering why I am interested in this, it is because I am refactoring some code to fully use generics, and searching for casts is one source of identifying candidates for genericity.

    cliffblob wrote:
    Better late than never?Yes!
    cliffblob wrote:
    ...The answer I found to ID unnecessary casts was, using Eclipse IDE, In compiler error and warning preferences to warn on unnecessary casts.Thanks for pointing IDEs out. I just opened IntelliJ, and going back to at least version 7.04 (maybe earlier) they have an inspection for "Redundant type cast".
    cliffblob wrote:
    I would still be interested to know if there is a way to identify casts in general in your source, perhaps now four years later there is a way?The only solutions that I can think of are either a complicated regex search, or you must use some tool like an IDE that understand Java syntax and can determine if a cast is happening.

  • Can I do dynamic class cast with java SE1.4.2?

    Hi,
    I have some question on dynamic class cast.
    I'm using java SE1.4.2. Suppose I have a method :
    castObjectToSomething(Object o)
    Something s = (Something) o;
    However, I don't know what is the class to cast until runtime. How can I do a runtime class cast?
    I know that java 5.0 have a Class.cast() method which java1.4.2 does not have. But can I do the same stuff by using SE1.4.2?
    Thank You!!!!!
    oh_silly

    There is no sense in wanting to cast to a class that is only known at runtime. Because you can't do anything with such a class during runtime. Even though you could technically retrieve the class name, the method names and the parameter names, you could do nothing with this class as you don't know what it is doing. If you would know what it can do, you would know it also during compile time and then you would know the classname/interface name you want to cast to and can import it and use it reasonably.
    Tell us the requirement that you think you have and we will proof you that you don't need such a requirement.

  • 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

  • Array Casting in java

    Hi,
    I am new to java.Last day Can I cast an arrays in java?For example casting an Object array to a String array or an integer array to a long one.If yes, then what are the rules and restrictions for casting arrays.I tried to google it, but I could not find any useful material.Could any one give me some links where I can get some useful material,books,mock tests etc. regarding preparation for SCJP 1.6?.Please help.
    Thanks in advance

    This is the Berkeley DB, Java Edition forum, and you should post only post questions about that product here. I think you may be looking for basic Java language information, and there are many other websites that can give you that information.

  • Simple Casting in Java--Any help is appreciated

    I'm new to Java programming and I'm in an introductory class in school. I'm trying to create a method that casts a double value into an integer and not sure if I'm doing this right.
    public int calculateFunction(int x) {
         return y = x + (x * x) + (Math.pow(2,x));
    Math.pow returns a double value that I need cast into an integer or I keep getting loss precision errors. Not sure how to accomplish this. Any help would be appreciated.

    public int calculateFunction(int x) {
         c = Math.pow(2,x);
         return y = x + (x * x) + (c);
         y = (int) c;
    }Any half-decent compiler should issue some diagnostics here ...
    Casting from type double to type int is done as follows:double dValue= ...; // something complicated here
    int iValue= (int)dValue; // get rid of all the fraction digits etc.So, replacing the 'dValue' by 'x+x*x+Math.pow(2, x)', this results in:int iValue= (int)(x+x*x+Math.pow(2, x));and since you want to return that value, you can simply replace this by:return (int)(x+x*x+Math.pow(2, x));kind regards,
    Jos

  • 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

  • Dynamic casting in java

    Hello everyone....
    i am having a problem as follows:
    i have a method in my project which is taking a reference of object type...
    i want to cast the object to the passing type,bt i dont want to cast explictily inside the method...
    can something be done by which the object itself get casted to passing type automatically by determining the runtime of the instance being passesd at runtime?
    public void change(Object o)
    /// i want to cast this object to A type without explicit casting.... can it be done through reflection or some other method?
    call of the above method from main///
    p.s.v.main(String[] args)
    A a =new A();
    a.call(new A());
    }

    807784 wrote:
    can something be done by which the object itself get casted to passing type automatically by determining the runtime of the instance being passesd at runtime?When you cast an Object to a specific class or interface you are telling the compiler that the object is really of that class or interface. The only thing a cast does at run time is to verify that the actual object is of the specified class. Hence, for a cast to do any good, it must be present at compile time.
    I don't know exactly what you are trying to do, but you might want to look at the visitor pattern.

  • Class casting, creating an image and decompiling...

    Hi, I've got a couple of questions:
    1)
    How can I fully decompile classes, so with the implementation of the methods? Is it always possible to fully decompile a class file? When is it and when not?
    2)
    I aks this questions before, but I still haven't got it working, so sorry, but I ask it again :) :
    I want to create my own class, for example cMyClass which extends the java.awt.Image class, which has abstract methods. How do these methods(for example getGraphics etc) have to be implemented?
    3)
    I can't cast a Image to cMyClass... why not?
    Someone told me he did the following:
    Canvas c = new Canvas()
    cMyClass oImage = (cMyClass) c.createImage (100, 100);
    and that this worked... I tried to do this too, and it seemed to work, but it actually didn't!!
    I found out that c.createImage returns a null reference!!! That's why Java was able to cast it to my own cMyClass (not a problem to cast a null to something else), but when I created a Image (by doing a lot of unnessacary difficult stuff), and then tried to cast this Image to cMyClass it throw a ClassCastException or something like that...
    How can I cast the java.awt.Image class to my class anyway?
    3)
    Why can't you create a image like i've done above or even like below:
    Canvas c = new Canvas()
    Image oImage = c.createImage (100, 100);
    Why does this return a null reference?
    Isn't there a better way to create an image?
    4)
    The getWidth and getHeight need a I thought observer...? Why is this? I just want the width and height and don't have an observer or something like that. Is there a way around this?
    I tried getWidth(null) but this returns -1
    Please help! :)

    Hi, I've got a couple of questions:
    1)
    How can I fully decompile classes, so with the
    implementation of the methods? Is it always possible
    to fully decompile a class file? When is it and when
    not?You can always get a dump of the bytecode with 'javap -c'. If you don't want to figure things out yourself, try searching google for a class file decompiler, possibly a de-obfuscator.
    De-compilation is completely possible if the original author wanted that, by including debugging information. Depending on the degree of such information and the amount of code obfuscation, the decompiled code may lack variable names, line numbers, field and method names, class names, and even code structure. Names and line numbers are usually not re-creatable automatically, since the information is simply lost, but you can replace them with your own strings when analyzing an unknown class file (using the correct tools). Re-creating the original code structure may work in some cases, but to me the general case looks rather close to the halt problem (i.e. not solvable).
    Use a de-obfuscator, hope you've got good luck, and analyze the bytecode manually if that doesn't work.
    2)
    I aks this questions before, but I still haven't got
    it working, so sorry, but I ask it again :) :
    I want to create my own class, for example cMyClass
    which extends the java.awt.Image class, which has
    abstract methods. How do these methods(for example
    getGraphics etc) have to be implemented?I don't really understand the problem. 'abstract' means on the language level that your subclass must provide an implementation, i.e. a method body. What that method is expected to do is explained in the javadocs for Image. But in fact you're free to do anything. You could play a sound in the getWidth() method (replace with any method name if you want). Just consider the fact that a lot of code calls getWidth in the hope of getting the width of the image, not playing a sound. So much about the language level.
    On a higher level, a subclass of Image should implement a certain way to describe an image. AFAIK this means that your code must know the size of the image and know how to produce the pixels of the image. I can't tell you in general how you must do this, because it depends on your special case. This boils down to the question, why do you want to write a subclass of 'Image'? What new way of describing and image have you come up with?
    3)
    I can't cast a Image to cMyClass... why not?Simple, and that's certainly not an ALT. Because that specific Image is not a cMyClass. It's probably a BufferedImage or similar that was produced by AWT.
    Please read the specs carefully what casting is about.
    Someone told me he did the following:
    Canvas c = new Canvas()
    cMyClass oImage = (cMyClass) c.createImage (100,
    100);
    and that this worked... I tried to do this too, and it
    seemed to work, but it actually didn't!!
    I found out that c.createImage returns a null
    reference!!! That's why Java was able to cast it to my
    own cMyClass (not a problem to cast a null to
    something else), but when I created a Image (by doing
    a lot of unnessacary difficult stuff), and then tried
    to cast this Image to cMyClass it throw a
    ClassCastException or something like that...
    How can I cast the java.awt.Image class to my class
    anyway?You can't, and if you understood casting then you'd understand that it wouldn't make sense.
    3, 4(don't know)
    Maybe stupid question, but for example the BufferedImage, is this
    completly written in Java?
    How is the link made between the OS+hardware and the Java code? I
    mean, displaying images etc. is very platform dependend not?Look for JNI (Java Native Interface). It's a way to link native (e.g. C) code with Java code.

Maybe you are looking for

  • How do I know if my computer has been hacked into?

    I am having two issues with my iMac. One is with my wireless -- in the past few days I've received a few times an IP address error, which seems to be solved by renewing the DHCP lease and restarting. Also, at the login screen when I restart, it takes

  • Preview slide show-but not full screen?

    Seems to me I recall seeing an option to NOT preview the slideshow full screen. But can't find it now. I would like to view the slide show while keeping Pages on screen so I can take notes. Is there any way to do that? Thanks.

  • Why won't the top row of letters type on mac book pro?

    The top row of letters won't type on my mac book pro and the "b" letter acts as a back space.

  • Windows Media Player Uninstall

    So I installed Windows Media Player on my new Macbook and decided to delete it an instead get flip4mac to play my .wmv. After instaling flip4mac I tried to draging my old Windows Media Player to the trash and everytime I try to delete it brings up an

  • How to Detect the Target Plataform

    Hi, I am new to Mobile Development I am using flash Builder 4.5.1. How can I detect the running target plataform so that I can adjust width and heights and adjust the layout of the components. Thanks in advance