Sunday, July 14, 2013

ClassCastException when subtype casting

    Object[] objects = new Object[10];
    String[] strings = (String[]) objects;
We all know that all objects in JAVA are drive from Object class. Does it true? If this statement is true then why the code shown above throw a ClassCastException in run-time? Now consider following code.
    String[] strings = new String[10];
    Object[] objects = (Object[]) strings;
    objects[0] = new String("simple Text");
The code compiles and execute successfully without error. And the content was print out at the end of the execution. Don't you think this is interesting? This code has prove that Object is holding a String in memory. I spent quite some time searching on this and I found this:
Java is a strongly typed language, and that means you can only cast an object to a type it extends from (either a superclass or an interface). –

No comments: