What is a ClassCastException and when it will be thrown in Java?

JavaObject Oriented ProgrammingProgramming

The java.lang.ClassCastException is one of the unchecked exception in Java. It can occur in our program when we tried to convert an object of one class type into an object of another class type.

When will be ClassCastException is thrown

  • When we try to cast an object of Parent class to its Child class type, this exception will be thrown.
  • When we try to cast an object of one class into another class type that has not extended the other class or they don't have any relationship between them.

Example

Live Demo

class ParentTest {
   String parentName;
   ParentTest(String n1){
      parentName = n1;
   }
   public void display() {
      System.out.println(parentName);
   }
}
class ChildTest extends ParentTest {
   String childName;
   ChildTest(String n2) {
      super(n2);
      childName = n2;
   }
   public void display() {
      System.out.println(childName);
   }
}
public class Test {
   public static void main(String args[]) {
      ChildTest ct1 = new ChildTest("Jai");
      ParentTest pt1 = new ParentTest("Adithya");
      pt1 = ct1;
      pt1.display();

      ParentTest pt2 = new ParentTest("Sai");
      ChildTest ct2 = (ChildTest)pt2;
   }
}

Output

Jai
Exception in thread "main" java.lang.ClassCastException: ParentTest cannot be cast to ChildTest
        at Test.main(Test.java:30)
raja
Published on 26-Jun-2019 22:29:32
Advertisements