【问题标题】:ClassCastException when trying to convert Interfaces尝试转换接口时出现 ClassCastException
【发布时间】: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,因此代码执行在运行时失败。 我说的对吗?

【问题讨论】:

  • 你的理解是正确的。 SampleClassChildInterface 无关。还有其他问题吗?还是您想确认的只是这些?
  • 有什么方法可以实现让 ChildInterface 返回的动机?
  • 不让SampleClass实现ChildInterface
  • 类似:公共类 SampleClass 实现 ParentInterface、ChildInterface ?
  • 只需将implements ChildInterface 声明为ChildInterface 已经扩展ParentInterface

标签: java oop interface classcastexception


【解决方案1】:

根据您的描述,我认为您忽略了一个类可以实现多个接口的事实。

在您的示例中,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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多