如何解决尝试转换接口时的ClassCastException
我正在寻求帮助,以了解为什么在尝试将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;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。