简体   繁体   中英

Generic Types and Interfaces Java

Having these classes and interfaces..

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>>();

When I try to add an instance of MyClass to the shapeCollections , Eclipse still asks to let MyClass implement ShapeCollection< Shape> when it already does since it implements ShapeCollection< Line> beeing Line an extension to Shape . I've tried to change to ShapeCollection< T extends Shape> with no results. Any help would be much appreciated.

You have declared type parameters whose name is Shape , Line etc. You have not declared a bound . That is, these two declarations are the same:

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

But what you want is:

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

When it comes to using it, if I read your question literally you are trying to add a MyClass to a List<ShapeCollection<Shape>> , but MyClass is not a collection of Shape but a collection of Line and Line extends Shape , you you must use ? extends Shape ? extends Shape as the type, not Shape :

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

This is because Collection<Line> is not a subclass of Collection<Shape> : Generics is not like class hierarchies.

According to the declarations you put MyClass does not implement ShapeCollection<Line> . And even if it did, it wouldn't matter. You can put only things that extends Shape and not things that extend ShapeCollection<Shape>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM