知识点:
- 接口和接口之间在进行强制转换时,无论是向上还是向下转型,没有继承关系也可以强转。
- 向下转型最好用if + instanceof运算符进行判断
错误提示:
D:\Java\Java进阶\异常集>java ClassCastException
Exception in thread “main” java.lang.ClassCastException: class C cannot be cast to class B (C and B are in unnamed module of loader ‘app’)
at ClassCastException.main(ClassCastException.java:9)
代码演示:
public class ClassCastException
{
public static void main(String[] arg)
{
//多态:父类型A引用a指向子类型C的对象
A a = new C();
//测试出:接口和接口之间在进行强制转换时,没有继承关系也可以强转
//编译不会出现问题,运行可能会出现ClassCastException异常。
//B b = (B)a;//编译不出错,运行出错。
//修改后
//当遇到需要向下转型时:用if 和instanceof进行判断两者之间是否有关联。
//这样可以避免异常出现
if(a instanceof B)
{
B b = (B)a;
}
}
}
//A接口(完全抽象类)
interface A
{
}
//B接口(完全抽象类)
interface B
{
}
//继承A接口的类C,接口继承用implements
class C implements A
{
}