I have an interface like this:
public interface SuperInterface {
public interface SubInterface {
public void get();
}
//**More interfaces*/
}
this method in my Toolkit, which retrieves all objects which are instance of a certain class:
public static <T> ArrayList<T> getSome(ArrayList<Object> objects, Class<T> clazz) {
ArrayList<T> result = new ArrayList<T>();
for (Object o : objects)
if (clazz.isInstance(o))
result.add(clazz.cast(o));
return result;
}
MyClass is not really interesting, its an empty class implementing from SuperInterface.SubInterface
And this piece in the main:
ArrayList<Object> mObjects = new ArrayList<Object>() {
{
add(new MyClass()); //SuperInterface.SubInterface
add(Integer.valueOf(5));
add(new String("Hello"));
add(new Object());
}
};
ArrayList<SuperInterface> mSuperInterfaces = Toolkit.getSome(mObjects, SuperInterface.class); //returns a zero-sized list.
ArrayList<SuperInterface.SubInterface> mSubInterfaces = Toolkit.getSome(mObjects, SuperInterface.SubInterface.class); //returns a one-sized list
The first method call does not work as I hoped, the second does. Is it possible so that the first one works without explicitly putting the subinterfaces in a different file and implementing the superclass? Because apparently the subinterfaces aren’t really subinterfaces, so I tried to make the Interface class like this:
public class ClassWithInterfaces {
public interface Super { }
public interface Sub implements Super { /**...*/ }
}
But apparently you can’t use implements in an inner interface.
My question is: Why is that, and is there a way to accomplish what I want to achieve (inner interfaces in one file)? I don’t necessarily need it, I merely want to know why it’s not possible to implement in inner interfaces (yet it’s possible to extend inner classes).
You’re looking for
extendsrather thanimplements:This compiles for me, and I can certainly implement both interfaces.
Since there appears to be some confusion around extending vs implementing, perhaps the following will help clear things up: