【问题标题】:Inheritance in Java with generics [duplicate]Java中的泛型继承[重复]
【发布时间】:2013-06-16 09:00:40
【问题描述】:

前几天我在写一个简单的Java程序,发现这段代码不起作用(它给出了编译时错误):

ArrayList<Document> docs = new ArrayList<Book>();

其中 Document 是一个接口,而 Book 实现了 Document。

为什么 Java 中的继承不适用于泛型?如果我想让该代码工作,我必须使用通配符,如下所示:

ArrayList<? extends Document> docs = new ArrayList<Book>();

我想知道这是什么原因?如果我需要一个 ArrayList of Documents,并且我知道 Book 也是一个 Document,为什么我不能将 Books 的 ArrayList 用作 Documents 的 ArrayList?

【问题讨论】:

标签: java


【解决方案1】:

考虑以下示例:

ArrayList<Book>books = new ArrayList<Book>();
ArrayList<Document> docs = new ArrayList<Book>();
docs.add(new Document());
Book book = books.get(0); //Oops, now we have a variable of type book, referring to a Document that is not a book. Not good.

如果您想了解更多关于此问题的概念性背景材料,请阅读Covariance and Contravariance

【讨论】:

  • 非常感谢,不知道如果我用 extends MyType> 我不能添加元素,只能读取它们。
【解决方案2】:

只是因为List&lt;U&gt; 的类型不能是List&lt;V&gt; 的子类型(除非 U = V)。

例如,如果您承认 List&lt;Integer&gt;List&lt;Number&gt; 的子类型。您可以编写以下内容:

void addPi(List<Number> l) {
 l.add(3.14);
}

List<Integer> l = new LinkedList<>();
addPi(l);

这里有什么问题?

【讨论】:

  • 非常感谢,没想到添加新项目会出现问题。
猜你喜欢
  • 1970-01-01
  • 2011-08-17
  • 1970-01-01
  • 2011-04-11
  • 1970-01-01
  • 1970-01-01
  • 2011-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多