我的代码中有这三个接口(interface):
public interface ParentInterface {
// some properties and methods
}
public interface ChildOne extends ParentInterface{
//some extra properties and methods
}
public interface ChildTwo extends ParentInterface{
//some extra properties and methods
}
我有一些功能void someFunc(List<ParentInterface>)
,它应该能够接受具有实现 ChildOne
的实例的混合列表。或ChildTwo
。但如果我有 List<ChildOne>
呢? ?有更好的方式调用 someFunc
比这个?
List<ChildOne> coList = new HashList<ChildOne>();
//add some items to coList
List<ParentInterface> piList = new HashList<ParentInterface>(coList.size());
piList.addAll(coList);
someFunc(piList);
我不能这样打电话someFunc(coList)
无需创建新列表?
最佳答案
正如 Jon Skeet 在评论中建议的那样,我将函数的签名更改为 void someFunc(List<? extends ParentInterface>)
这就像一个魅力!
关于java - 有没有办法在 JAVA 接口(interface)及其特化之间进行转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34725484/