ClassCastException In Java: In this post, we are going to discuss ClassCastException. A class cast exception is thrown by Java when you try to cast an Object of one data type to another. Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.
ClassCastException In Java
As you can see in the above pic ClassCast-Exception exception extends the class RuntimeException and thus, belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM). It is an unchecked exception and thus, it does not need to be declared in a method’s or a constructor’s throws clause.
java.lang.classcastexception In Java:
An object can be automatically upcasted to its superclass type. You need not mention class type explicitly. But, when an object is supposed to be downcasted to its subclass type, then you have to mention class type explicitly. In such a case, there is a possibility of occurring class cast exception. Most of the time, it occurs when you are trying to downcast an object explicitly to its subclass type.
package co.java.exception; public class ClassCast_Exception { public static void main(String[] args) { Object obj=new Object(); int i=(int) obj; System.out.println(i); } }
Lets Run The Above Program:
When we run the above program we got the below error:
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.Integer at co.java.exception.ClassCastException.main(ClassCast-Exception.java:8)
Let’s take another example:
package co.java.exception; class Parent { public Parent() { System.out.println("An instance of the Parent class was created!"); } } final class Child extends Parent { public Child() { super(); System.out.println("An instance of the Child class was created!"); } } public class ClassCast-ExceptionExample { public static void main(String[] args) { Parent p = new Parent(); Child ch = new Child(); ch = (Child) p; //This statement is not allowed. } }
If we run the program then we will get
An instance of the Parent class was created! An instance of the Parent class was created! An instance of the Child class was created! Exception in thread "main" java.lang.ClassCastException: co.java.exception.Parent cannot be cast to co.java.exception.Child at co.java.exception.ClassCastExceptionExample.main(ClassCastExceptionExample.java:20)
Explanation:
In The Above Program, we are creating an instance of both the parent and child class. but when we are trying to assign the parent class instance to child class instance that will generate an exception.
Ref: Article
Leave a Reply