什么是 ClassCastException 以及它何时会在 Java 中被抛出?\n
java.lang.ClassCastException 是 Java 中的一种未经检查的异常。当我们尝试将一个某个类类型的对象转换为另一个类类型的对象时,可能会在我们的程序中发生这种情况。
ClassCastException 何时会被抛出
- 当我们尝试将父类对象强制转换为其子类类型时,将抛出此异常。
- 当我们尝试将一个类对象强制转换为另一个没有继承该类或它们之间没有任何关系的类类型时。
示例
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; } }
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
输出
Jai Exception in thread "main" java.lang.ClassCastException: ParentTest cannot be cast to ChildTest at Test.main(Test.java:30)
广告