【发布时间】:2012-07-04 14:04:00
【问题描述】:
考虑以下代码:
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 作为标记接口,以仅在第一个列表中保留某些子类型,并在第二个列表中允许任何子类型。
【问题讨论】:
标签: java class interface casting