java - 有没有办法在 JAVA 接口(interface)及其特化之间进行转换?

标签 java oop interface

我的代码中有这三个接口(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/

相关文章:

objective-c - 声明 Objective C 对象时哪个更有效

php - 为什么人们在他们的 PHP 框架中使用单例

java - 当我从扩展特定接口(interface)的类创建对象时,我可以在使用该接口(interface)的地方使用该对象吗?

java - 如何解析多项式表达式以计算其根?

java - 如何初始化 Cloud Firestore Bean 以在所有包中使用?

c++ - 复制构造函数和 getter 错误(增变函数)

java - 在嵌套枚举实现接口(interface)中继承泛型类型

协议(protocol)中常量的快速初始化

java - 数据库连接应该始终保持打开状态还是仅在需要时才打开?

java - sparql 查询药物相互作用。小错误