【发布时间】:2020-09-08 05:58:20
【问题描述】:
我正在寻求帮助以了解为什么在尝试将 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();
}
}
运行时失败并出现异常
线程“主”java.lang.ClassCastException 中的异常:
我的理解:
此异常是由于我正在创建一个由 ParentClass 实现的对象,因此引用是针对 ParentInterface 而不是 ChildInterface,因此代码执行在运行时失败。 我说的对吗?
【问题讨论】:
-
你的理解是正确的。
SampleClass与ChildInterface无关。还有其他问题吗?还是您想确认的只是这些? -
有什么方法可以实现让 ChildInterface 返回的动机?
-
不让
SampleClass实现ChildInterface -
类似:公共类 SampleClass 实现 ParentInterface、ChildInterface ?
-
只需将
implements ChildInterface声明为ChildInterface已经扩展ParentInterface。
标签: java oop interface classcastexception