This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
Can someone please make me clear the concept of 'ClassCastException'. Consider this example : class superA { public void hello() { System.out.println("Hello"); } } public class subClass extends superA { public static void main(String ar[]) { Object obj = "hello";// 1 String a=(String) obj;// 2 System.out.println(a); superA supA = new superA(); // 3 subClass objRef =(subClass) supA;// 4 } } In 3 a superclass reference is created and i am assigning to a subclass reference. Same is done in the case of 1, But(2) it is not showing a runtime error where as (4) is showing an runtime error. Why???
Hi Jait, (2) is not showing an error as "obj" really references a String object. (4) is showing an error because "supA" is not really a "subClass" object. Java uses "dynamic binding" ... this means the type of the actual object, at runtime, will be checked to see if it really is an object of the cast type. If it isn't an error is produced. Hope that helps.
------------------ Jane Griscti Sun Certified Programmer for the Java� 2 Platform
This will give a ClassCastException at runtime as Object o does not contain a String at runtime. While the below code works fine .
Object o = new String("a"); String s = (String) o;
As object o contains a String value at runtime.
[This message has been edited by Angela Narain (edited September 14, 2001).] [This message has been edited by Angela Narain (edited September 14, 2001).]
Jait Thomas
Greenhorn
Joined: Feb 01, 2001
Posts: 13
posted
0
Hello Jane, Still I am not clear with the description. Can you please modify the above example such that the casting between two classes work properly. I don't think that toString() method has anything to do with that, isn't it. Thanks in Advance. Jait
james hoskins
Ranch Hand
Joined: Jun 28, 2001
Posts: 31
posted
0
Hello Jait, Jane is right, the compiler doesn't check object types just reference types. It looks at line //4 and sees a cast of reference supA of type SuperA to SubClass, it can check that SubClass extends SuperA and so it is possible that supA refers to a SubClass object at runtime an so the compiler allows the cast. At runtime, however, the reference can be properly linked to an object - the old "dynamic binding" - and can be seen to refer to a SuperA object. This won't be allowed. To make your code work, why don't you change statement at //3 to: SuperA supA = new SubClass(); then the compiler and runtime environment will be very happy. kind regards, james hoskins.
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.