Java泛型:为什么内部接口无法实现(内部)超级接口?

5

I have an interface like this:

public interface SuperInterface {
    public interface SubInterface {
        public void get();
    }
    //**More interfaces*/

}

我工具箱中有一个方法,它可以检索所有属于某个类的对象:

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;
}

我的类并不是特别有趣,它只是一个实现了SuperInterface.SubInterface的空类。

而在主函数中的这一段:

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

第一个方法调用并不像我希望的那样工作,第二个则可以。是否可能使第一个方法调用正常工作而无需将子接口显式放在不同的文件中并实现超类?因为 显然子接口并不是真正的子接口,所以我尝试将Interface类做成这样:

public class ClassWithInterfaces {
  public interface Super { }
  public interface Sub implements Super { /**...*/ }
}

但显然你不能在内部接口中使用implements

我的问题是:为什么,是否有一种方法可以实现我想要的目标(在一个文件中使用内部接口)?我不一定需要它,我只是想知道为什么不能在内部接口中实现(而在内部类中扩展是可能的)。

2个回答

6
但是显然你不能在内部接口中使用implements。你需要用extends而不是implements
public class ClassWithInterfaces {
  public interface Super { }
  public interface Sub extends Super { /**...*/ }
}

这对我来说是可以编译的,我肯定能够实现两个接口。

由于在扩展和实现方面似乎存在一些混淆,也许以下内容可以帮助澄清问题:

  • 一个接口扩展另一个接口。
  • 一个类实现一个接口。
  • 一个类扩展另一个类。

从什么时候开始可以从接口扩展?我以为关键字implements和extends是用来区分抽象类和接口的? - stealthjong
2
@ChristiaandeJong:接口总是扩展其他接口,它们从不实现它们。只有类能够去实现事物。 - NPE
既然你提到了,这其实很合乎逻辑。非常感谢。 - stealthjong

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接