gpt4 book ai didi

java - 子类/接口(interface)和父类(super class)之间的转换

转载 作者:行者123 更新时间:2023-11-30 04:44:40 24 4
gpt4 key购买 nike

考虑以下代码:

interface IFace {}

abstract class Supertype {}

class Subtype1 extends Supertype implements IFace {}
class Subtype2 extends Supertype implements IFace {}
class Subtype3 extends Supertype {}

class Foo {
//Contains elements of Subtype1 and Subtype2
List<IFace> ifaceList = new ArrayList<IFace>();

//Contains elements of Subtype1, Subtype2, and Subtype3
List<Supertype> superList = new ArrayList<Supertype>();

void CopyItem() {
superList.add( (Supertype) ifaceList.someElement() );
}
}

如果我知道只有子类型会实现 IFace,将 IFace 元素转换为 Supertype 是否安全?是否有可能确保只有子类型才会实现 IFace

我尝试使用 IFace 作为标记接口(interface),仅在第一个列表中保留某些子类型,并允许在第二个列表中使用任何子类型。

最佳答案

Is it safe to cast an IFace element to Supertype if I know that only Subtypes will implement IFace?

是的。

Is it even possible to ensure that?

如果您的意思是“是否可以确保只有 Supertype 的子类实现 IFace” - 不。接口(interface)可以由任何东西实现。

如果您的意思是“是否可以确保转换成功” - 是的,您可以在转换之前使用 instanceof

关于java - 子类/接口(interface)和父类(super class)之间的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11330636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com