小编gre*_*ell的帖子

继承和集合相关的编译错误

我想弄清楚为什么这段代码不能编译.

我有接口A扩展的接口B.类C实现接口B.

当我调用一个接收A类单个对象的方法时,我可以传入一个C类型的对象,这很好.

当我调用一个接收类型为A的java.util.List的方法时,我无法传入类型为C的对象的java.util.List.Eclipse会生成以下错误:类型为Test1的方法addAList(List)不适用于参数(List)

源代码示例如下.

import java.util.ArrayList;
import java.util.List;

public class Test1 {

    public void addASingle(A a) {
        return;
    }

    public void addAList(List<A> aList) {
        return;
    }

// **********************************

    public static void main(String[] args) {
        Test1 t = new Test1();

        C c1 = new C();
        List<C> cList = new ArrayList<C>();
        cList.add(c1);

        t.addASingle(c1); // allowed

        t.addAList(cList);  // The method addAList(List<Test1.A>)
    // in the type Test1 is not applicable for the arguments (List<Test1.C>)
    }

// **********************************

    public static interface A {
    } …
Run Code Online (Sandbox Code Playgroud)

java collections inheritance interface

2
推荐指数
1
解决办法
99
查看次数

标签 统计

collections ×1

inheritance ×1

interface ×1

java ×1