ste*_*ong 5 java generics inheritance interface
我有这样的界面:
public interface SuperInterface {
public interface SubInterface {
public void get();
}
//**More interfaces*/
}
Run Code Online (Sandbox Code Playgroud)
我的Toolkit中的这个方法,它检索作为某个类的实例的所有对象:
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;
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
第一个方法调用不能像我希望的那样工作,第二个方法调用.是否有可能使第一个工作没有明确地将子接口放在不同的文件中并实现超类?因为显然子接口不是真正的子接口,所以我试图使接口类像这样:
public class ClassWithInterfaces {
public interface Super { }
public interface Sub implements Super { /**...*/ }
}
Run Code Online (Sandbox Code Playgroud)
但显然你不能implements在内部界面中使用.
我的问题是:为什么会这样,有没有办法实现我想要实现的目标(一个文件中的内部接口)?我不一定需要它,我只是想知道为什么不可能在内部接口中实现(但是可以扩展内部类).
但显然你不能
implements在内部界面中使用.
你正在寻找extends而不是implements:
public class ClassWithInterfaces {
public interface Super { }
public interface Sub extends Super { /**...*/ }
}
Run Code Online (Sandbox Code Playgroud)
这为我编译,我当然可以实现这两个接口.
由于在扩展与实施之间似乎存在一些混淆,因此以下内容可能有助于澄清问题:
| 归档时间: |
|
| 查看次数: |
1149 次 |
| 最近记录: |