Why ClassCastException Occurs?
API specification for ClassCastException says that “Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance”.
for example, when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.
ClassCastException is an unchecked exception i.e. it is not identified at compile time. It is a runtime exception.
Let’s understand this through following example:
1
2
3
4
5
6
| class ClassCastExceptionDemo { public static void main(String args[]) { Object obj = new Integer(04); System.out.println("The value is " + (String) obj); // ClassCastException occurs here }} |
Explanation
Here the first statement is well written & It produces no error. We know that java.lang.Object is super class for every class in Java, of course for java.lang.Integer too. We also know that, a super classreference variable can hold a sub class object. But when you do so, remember that you’ll not be able to call the sub class object’s own methods (the methods that were not inherited from the super class and belong to the sub class only),for example intValue(). The method intValue() is defined only injava.lang.Integer not in java.lang.Object. From the above statement, you cannot call ob.intValue(), this produces a compile time error.
See the next statement, the Object class reference ob is holding the object of it’s sub classjava.lang.Integer which is not a super class of the String class. When you do such a type cast between classes, it means that you are type casting objects not references. Though the reference is of the typejava.lang.Object which is a super class of java.lang.String, the object ob is holding the java.lang.Integerobject and you cannot type cast java.lang.Integer into java.lang.String.
No comments:
Post a Comment