ClassCastException in java

ClassCastException class is available in java.lang package and it extends RuntimeException class. It is an unchecked exception.


public class ClassCastException extends RuntimeException


ClassCastException class inherits methods from java.lang.Object class and java.lang.Throwable class.

Hierarchy of ClassCastException


Object => Throwable => Exception => RuntimeException => ClassCastException

When ClassCastException Occurs


ClassCastException occurs whenever one object is unable to cast of its subclass.

For example, this is the one case, whenever a super class object is casting to the subclass of it’s.

An Object is the super class of all Java classes either directly or indirectly. In the below example Object class(super class) instance holds integer value and casting to String class(subclass).

Example:



package com.exceptions;
public class CCastExceptionTest {
       public static void main(String[] args) {       
              Object obj=101;
             String s=(String) obj;          
              System.out.println(s); //ClassCastException
       }
}


Output:



Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
       at com.exceptions.CCastExceptionTest.main(CCastExceptionTest.java:5)


Another Example of ClassCastException



package com.exceptions;
class Super{
      
}
public class Sub extends Super{
       public static void main(String[] args) {       
              Super obj1=new Super();
              Sub obj2=new Sub();
              obj2=(Sub) obj1;          
       }
}


Output:



Exception in thread "main" java.lang.ClassCastException: com.exceptions.Super cannot be cast to com.exceptions.Sub
       at com.exceptions.Sub.main(Sub.java:10)



in the above example, we tried to cast super class object obj1 to subclass obj2.

No comments:

Post a Comment