繁体   English   中英

尝试转换接口时出现 ClassCastException

[英]ClassCastException when trying to convert Interfaces

我正在寻求帮助以了解为什么在尝试将 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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM