首页 > 解决方案 > 两个相互引用的通用接口

问题描述

我正在尝试编写两个泛型类/接口 Tile ( interface Tile<S extends Side<? extends Tile<S>>>) 和 Side ( abstract class Side<T extends Tile<? extends Side<T>>>),其中一个接口的泛型类型引用了另一个接口。

现在,当我尝试像这样实现 Tile 接口时:

public abstract class TileImpl<S> implements Tile<S extends Side<? extends Tile<S>>

我必须继续写 S 类型的界限:

S extends Side<? extends Tile<S>>

我怎样才能使这段代码工作?

public interface Tile<S extends Side<? extends Tile<S>>> {

    S getSide(Direction d);

    /**
     * Returns true if the current instance of Tile and the Tile t
     * fit together.
     * @param t a tile adjacent to the current tile
     * @param d the position of the tile t with respect to the current tile
     * @return true if the current tile and the tile t fit together
     */
    boolean fitsWith(Tile<S> t, Direction d);
}

public abstract class Side<T extends Tile<? extends Side<T>>> {
    private final T parent;

    public Side(T parent) {
        this.parent = parent; 
    }

    public T getParent() {
        return parent;
    }
}

标签: javagenerics

解决方案


public abstract class TileImpl<S> implements Tile<S extends Side<? extends Tile<S>>

你的问题是你已经在S使用它的地方而不是在它声明的地方设置了界限。所以只需将边界移动到正确的位置。

public abstract class TileImpl<S extends Side<? extends Tile<S>>> implements Tile<S>

推荐阅读