问题描述
我正在寻求帮助,以了解为什么在尝试将ParentInterface转换为ChildInterface时为什么会收到ClassCastException。
示例代码
{ParentInterface P1}
{SampleClass P2 implements P1}
{ChildInterface C1 extends P1}
SampleClass sampleClass = new SampleClass();
ChildInterface childI = (ChildInterface) sampleClass;
要具体说明正在做什么[上述逻辑的实现]:
getInterface(){
return (ChildInterface)ParentInterfaceHelper.INSTANCE;
}
private static class ParentInterfaceHelper {
private static final ParentInterface INSTANCE;
static{
INSTANCE = new SampleClass();
}
}
运行时出现异常失败
线程“ main”中的异常java.lang.classCastException:
我的理解:
此异常是由于当我创建由ParentClass实现的对象时,所以该引用是针对ParentInterface而不是ChildInterface的,因此代码在运行时执行失败。 我说的对吗?
解决方法
根据您的描述,我认为您错过了一个类可以实现多个接口的事实。
在您的示例中,SampleClass仅实现ParentInterface,而不实现ChildInterface。您可以让SampleClass实现ChildInterface,它也将隐式地实现ParentInterface。您还可以添加其他接口。
class SampleClass implements ChildInterface1,ChildInterface2
public class ParentInterfaceHelper {
private static final SampleClass INSTANCE;
static{
INSTANCE = new SampleClass();
}
public static ParentInterface getParentInterface(){
return INSTANCE;
}
public static ChildInterface1 getInterface1(){
return INSTANCE;
}
public static ChildInterface2 getInterface2(){
return INSTANCE;
}
}