When I compile and run the code presented above then a Class Cast Exception at f = (Float)ob occurs. C:\Java\EigeneJavaProgramme>java forex2 Float is Subclass of Object java.lang.ClassCastException: java.lang.Object at forex2.main(forex2.java:9) Exception in thread "main" I don’t understand that. I always thought a class cast exception is only thrown if you explicitly cast an object into an instance of another class which is not related by inheritance Appreciate your answers. Thomas
Joined: Mar 08, 2001
C:\Java\EigeneJavaProgramme>java CastTest2a java.lang.ClassCastException: Tree at CastTest2a.main(CastTest2a.java:10) Exception in thread "main"
//yes, a Float wrapper class is an object, so you can assign an Object reference to this Float object. Object objRef = new Float(9f); //The object never forget who she is (Float), so this will call the toString() method in the Float object System.out.println(objRef.toString()); //now I think I need to invoke method only available in the Float Object, So i assign it to a Float reference //As i am doing down casting, I need to make an explicit cast like this: Float ft = (Float) objRef; The code u have in your first posting will throw a class cast exception because the first object u are creating is an Object (it will always be). It is not a Float wrapper, so it wont work if u down cast it to a Float. But u can change a string to a float with the following code: String s = "9F"; Float f = Float.valueOf(s);
It is simply assigned to a pointer of type Tree. Ba! Mr. C# probably meant to say that it is assigned to a reference of type Tree. When does Class Cast Exception occur? From the documentation (mostly): A ClassCastException is thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException: Object x = new Integer(0); System.out.println((String)x); Where as the following code would not create a ClassCastException: Object x = new Integer(0); System.out.println((Integer)x);
Hello, may I understand it this way: If I EXPLICITLY cast an instance of a class into an instance of another class then a ClassCastException will occur if it is no SUBCLASS. Is this ok? Thomas
Joined: Dec 10, 2001
Maybe, kinda, almost. It really helped me (and what I stress whenever I'm teaching Java concepts to new programmers is) to learn to recognize the seperate concept of the object and the reference to the object. You cannot change the type of an object. A casting operator doesn't change the type of an object. It takes a reference of some type, and creates a reference of another type that refers to the same object that the original reference referenced. If the object is not actually of the type that you made a reference for, then a ClassCasteException will occur. Did that help any?