Object i = Integer.valueOf(42);
String s = (String)i; // ClassCastException thrown here.
# 3 楼答案
考虑一个例子,
class Animal {
public void eat(String str) {
System.out.println("Eating for grass");
}
}
class Goat extends Animal {
public void eat(String str) {
System.out.println("blank");
}
}
class Another extends Goat{
public void eat(String str) {
System.out.println("another");
}
}
public class InheritanceSample {
public static void main(String[] args) {
Animal a = new Animal();
Another t5 = (Another) new Goat();
}
}
在Another t5 = (Another) new Goat():您将得到一个ClassCastException,因为您无法使用Goat创建Another类的实例
Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because it's a dog.
Cat c = (Dog) a; // Will cause a compiler error for type mismatch; you can't cast a dog to a cat.
# 1 楼答案
这真的很简单:如果您试图将类A的对象类型转换为类B的对象,但它们不兼容,则会出现类转换异常
让我们考虑一组类
# 2 楼答案
直接从^{} 的API规范:
因此,例如,当试图将
Integer
强制转换为String
时,String
不是Integer
的子类,因此将抛出ClassCastException
# 3 楼答案
考虑一个例子,
在
Another t5 = (Another) new Goat()
:您将得到一个ClassCastException
,因为您无法使用Goat
创建Another
类的实例注意:转换仅在类扩展父类且子类强制转换为其父类的情况下有效
如何处理
ClassCastException
:Source of the Note and the Rest
# 4 楼答案
当您尝试将一种数据类型的对象强制转换为另一种数据类型时,Java会引发类强制转换异常
Java允许我们将一种类型的变量转换为另一种类型,只要转换发生在兼容的数据类型之间
例如,可以将字符串转换为对象,类似地,可以将包含字符串值的对象转换为字符串
示例
假设我们有一个HashMap,其中包含许多ArrayList对象
如果我们编写这样的代码:
它将抛出类强制转换异常,因为哈希映射的get方法返回的值将是数组列表,但我们正试图将其强制转换为字符串。这将导致异常
# 5 楼答案
如果您试图向下转换一个类,但实际上该类不是该类型,则会发生异常
考虑这一层次:
您可能有一个名为:
如果使用此代码调用:
它可以很好地编译,但在运行时您会得到一个
ClassCastException
,因为o实际上是一种动物,而不是一只狗在Java的更高版本中,您会收到编译器警告,除非您:
# 6 楼答案
你了解铸造的概念吗?强制转换是类型转换的过程,在Java中非常常见,因为它是一种静态类型语言。一些例子:
通过
Integer.parseInt("1")
->;将字符串"1"
强制转换为int
;没问题将字符串
"abc"
强制转换为int
->;引发一个ClassCastException
或者考虑一个带有
Animal.class
、Dog.class
和Cat.class
的类图