【问题标题】:How to call a method with List<Child>, but method's parameter is List<Parent>?如何用 List<Child> 调用方法,但方法的参数是 List<Parent>?
【发布时间】:2014-01-31 10:36:43
【问题描述】:

我遇到了一些问题,我不明白为什么它不起作用。 我有一个父类:

public abstract class Parent {
    ...
}

和 2 个子类:

public class Child1 extends Parent {
    ...
}

public class Child2 extends Parent {
    ...
}

我有一个方法,它正在处理子列表。但它应该适用于 Child1 和 Child2 类型,所以我认为它应该可以工作:

public static void doSomething(List<Parent> list) {
    ...
}

我就是这样称呼它的:

List<Child1> children = dao.getChildren("1");
doSomething(children);

List<Child2> children2 = dao.getChildren("2");
doSomething(children2);

但它不起作用,它显示这个错误:

The method doSomething(List<Parent>) in the type MyClass is not applicable for the arguments (List<Child1>)
The method doSomething(List<Parent>) in the type MyClass is not applicable for the arguments (List<Child2>)

我该如何编写这段代码?

【问题讨论】:

  • doSomething() 返回什么?您的代码未显示返回类型
  • 我更新了,很抱歉,但不管那个方法做什么
  • 啊,我读的太快了,以为你在做 List children = doSomething(chidren)。事后看来有点傻:)

标签: java inheritance parent extends


【解决方案1】:

哦,我做到了!此代码适用于 doSomething 方法:

public static void doSomething(List<? extends Parent> list) {
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2023-03-06
    • 2010-11-13
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 2020-05-30
    相关资源
    最近更新 更多