ClassCastException in java

ClassCastException is a RunTimeException or unchecked exception which occurs when JVM unable to cast an object of one type to another type.

Constructors of ClassCastException

  • ClassCastException()

    It creates an instance of the ClassCastException class.

  • ClassCastException(String s)

    It creates an instance of the ClassCastException class by using the specified string as message.

Note: ClassCastException is related to casting of objects from one type to another. In java, up-casting is done implicitly (sub class object cast to super class type) i.e. no explicit conversion is required but in case of down-casting there is no implicit conversion. We need to explicitly cast super class object to sub class type which results into the possibilities of ClassCastException.

Example

class SuperClass {
    public SuperClass() {
        System.out.println("Inside SuperClass constructor.");
    }
}
 
final class SubClass extends SuperClass {
    public SubClass() {
        System.out.println("Inside SubClass constructor.");
    }
}
 
public class Main {
    public static void main(String[] args) {
        SuperClass superObject = new SuperClass();
        SubClass subObject = new SubClass();
        superObject = subObject; // Valid statement
        subObject = superObject; //Class cast exception here
    }
}

Output

Main.java:18: error: incompatible types: SuperClass cannot be converted to SubClass
        subObject = superObject; //Class cast exception here
                    ^
1 error

How to prevent ClassCastException

  • We need to careful in case of down-casting. New object type should one of it’s super class.
  • Use Generics, which provides compile time checking.

Java interview questions on Exception Handling

Content Protection by DMCA.com
Please Share