Java 子类/接口和超类之间的转换
考虑以下代码:Java 子类/接口和超类之间的转换,java,class,interface,casting,Java,Class,Interface,Casting,考虑以下代码: 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 an
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{}
抽象类超类型{}
类子类型1扩展了超类型,实现了IFace{}
类子类型2扩展了超类型,实现了IFace{}
类子类型3扩展了超类型{}
福班{
//包含子类型1和子类型2的元素
列表ifaceList=newarraylist();
//包含子类型1、子类型2和子类型3的元素
List superList=new ArrayList();
void CopyItem(){
添加((超类型)ifaceList.someElement());
}
}
如果我知道只有子类型将实现IFace
,那么将IFace
元素强制转换为Supertype
安全吗?甚至可以确保只有子类型才能实现IFace吗
我试图使用IFace
作为标记接口,在第一个列表中只保留某些子类型,而在第二个列表中允许任何子类型
如果我知道只有子类型才能实现IFace,那么将IFace元素强制转换为超类型安全吗
对
甚至有可能确保这一点吗
如果您的意思是“是否可以确保只有Supertype
的子类实现IFace
”—否。接口可以通过任何方式实现
如果您的意思是“是否有可能确保强制转换成功”-是的,您可以在强制转换之前使用
instanceof
。最安全的方法是使用Supertype implement IFace。如果不可能,那么可以将IFace元素强制转换为超类型,只要实现IFace的每个类都是超类型子类。您必须确保这一点暂时是正确的,这很容易出错
如果我知道只有子类型才能实现IFace,那么将IFace元素强制转换为超类型安全吗
如果您确定所有IFace元素也扩展了超类型,那么这就不会是问题。但在未来,这可能不再是事实
甚至有可能确保这一点吗
对。您可以尝试捕获ClassCastException,或者在使用运算符instanceof
void CopyItem() {
IFace obj = ifaceList.someElement();
if (obj instanceof Supertype) superList.add( (Supertype)obj );
else System.err.println("WARNING: IFace object is not a Supertype.");
}
如果我只知道,将IFace元素强制转换为超类型安全吗
子类型将实现IFace
如果您知道自己的代码,并且实现IFace
的每个类也是Supertype
的子类,那么没有问题,但是您可以始终使用instanceof
操作符检查Supertype
甚至有可能确保这一点吗
考虑对代码进行以下修改:
interface IFace {}
abstract class Supertype {}
abstract class SupertypeAndFace extends Supertype implements IFace {}
class Subtype1 extends SupertypeAndFace {}
class Subtype2 extends SupertypeAndFace {}
class Subtype3 extends Supertype {}
class Foo {
//Contains elements of Subtype1 and Subtype2
List<SupertypeAndFace> ifaceList = new ArrayList<SupertypeAndFace>();
//Contains elements of Subtype1, Subtype2, and Subtype3
List<Supertype> superList = new ArrayList<Supertype>();
void CopyItem() {
superList.add(ifaceList.someElement());
}
}
实例。。。。。(我明白你的意思,但我想你也明白我的意思)。@assylias:不知道你在这里是什么意思。你可以确保演员是安全的,但据我所知,这不是OP想要确保的。这就是我的意思,是的。不确定它是否是问题。请考虑<代码> IFace < /Cord>标记接口,以确保只有某些子类型在第一个列表中,但是任何子类型可以在第二个列表中。有更好的方法吗?@BrianTempleton:啊,我明白了-虽然
IFace
的所有实现都是Supertype
子类,但并非所有子类都实现IFace
。我已经删除了我答案的最后一部分。
void CopyItem() {
if (ifaceList.someElement() instanceof Supertype) {
superList.add( (Supertype) ifaceList.someElement() );
} else {
// Throw exception if necessary
}
}