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
- what is an exception?
- How the exceptions are handled in java?
- What is the difference between error and exception in java?
- Can we keep other statements in between try catch and finally blocks?
- Explain the exception hierarchy in java?
- What are runtime exceptions in java?
- What is outofmemoryerror in java?
- What are checked and unchecked exceptions in java?
- What is the difference between classnotfoundexception and noclassdeffounderror in java?
- Will finally block get executed if return?
- Can we throw an exception without throws?
- What is rethrowing an exception in java?
- What is the use of throws keyword in java?
- What is exception propagation in java?
- Difference between throw and throws in java?
- What is finally in java?
- What is the difference between final finally and finalize in java?
- How to create customized exceptions in java?
- What is classcastexception in java?
- What is stackoverflowerror in java?
- What is the superclass of all exception classes?
- What is the use of printstacktrace method in java?
- What is arraystoreexception in java?