2012-12-11 77 views
5

我有一个这样的接口:Java泛型:为什么内部接口不能实现(内部)超级接口?

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

MyClass的是不是真的很有趣,它的空类从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 

第一个方法调用不能像我希望的那样工作,第二个方法调用不起作用。是否有可能使第一个工作没有明确地将子接口放入不同的文件并实现超类?由于显然子接口是不是真的子接口,所以我试图让界面类是这样的:

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

但很显然,你不能在一个内部接口使用implements

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

回答

6

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

您正在寻找extends而不是implements

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

这编译对我来说,我当然可以实现这两个接口。

由于似乎周围延伸VS实施一些混乱,也许下面将有助于明确的东西:

  • 接口扩展另一个接口。
  • A类实现了接口。
  • A类延伸另一类。
+0

从什么时候可以从接口扩展?我认为关键字在那里实现并扩展以区分抽象类和接口? – stealthjong

+2

@ChristiaandeJong:一个接口总是*扩展*其他接口,它从不*实现*它们。只有一个班可以实施。 – NPE

+0

现在你提到它,它确实很合乎逻辑。非常感谢。 – stealthjong