通用类型和接口Java

时间:2013-10-19 13:26:56

标签: java generics interface

拥有这些类和接口..

public interface Shape;

public interface Line extends Shape

public interface ShapeCollection< Shape>

public class MyClass implements ShapeCollection< Line>

List< ShapeCollection< Shape>> shapeCollections = new LinkedList< ShapeCollection< Shape>>();

当我尝试向MyClass添加shapeCollections的实例时,Eclipse仍然要求MyClass实现ShapeCollection< Shape>,因为它实现了ShapeCollection< Line>蜜蜂Line Shape的扩展名。我试图更改为ShapeCollection< T extends Shape>但没有结果。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

您已声明名称ShapeLine等类型参数。您尚未声明绑定。也就是说,这两个声明是相同的:

public interface ShapeCollection<Shape> // generic parameter called Shape
public interface ShapeCollection<T>  // generic parameter called T

但你想要的是:

public interface ShapeCollection<T extends Shape> // generic parameter bound to Shape

在使用它时,如果我从字面上阅读您的问题,您尝试将MyClass添加到List<ShapeCollection<Shape>>,但MyClass不是Shape的集合但是LineLine的集合扩展了Shape,您必须使用? extends Shape作为类型,而不是Shape

List<ShapeCollection<? extends Shape>> shapeCollections = new LinkedList<ShapeCollection<? extends Shape>>();
shapeCollections.add(new MyClass()); // should work

这是因为Collection<Line> 不是Collection<Shape>的子类:泛型不像类层次结构。

答案 1 :(得分:1)

根据你提出的声明MyClass没有实现ShapeCollection<Line>。即使它确实如此,也没关系。您只能放置扩展Shape的内容而不扩展ShapeCollection<Shape>

的内容