Consider the following code:
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() );
}
}
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 only Subtypes will implement IFace?
I’m trying to use IFace as a marker interface to keep only certain Subtypes in the first list and allow any Subtypes in the second list.
Yes.
If you mean “is it possible to ensure that only subclasses of
SupertypeimplementIFace” – no. An interface can be implemented by anything.If you mean “is it possible to ensure that the cast will succeed” – yes, you can use
instanceofbefore casting.