从接口继承扩展泛型类型

时间:2013-06-17 22:09:00

标签: java generics inheritance

我担心我错误地表达了这个问题,所以这里有一个例子来说明:

我有一个界面:

public interface ICard  extends Comparable<T>{

    public abstract String toString();

    public abstract int compareTo(T o) throws WrongCardTypeException;

}

我想要的是实现ICard的类自动实现Comparable<T>,这样你只能比较任何类实现ICard

相反,我需要为可比扩展指定通用,并使用下面的instancof检查

public interface ICard  extends Comparable<ICard>{

    public abstract String toString();

    public abstract int compareTo(ICard o) throws WrongCardTypeException;

}

public class PlayingCard implements ICard{
    public enum Rank { TWO, THREE, FOUR, FIVE, SIX,
        SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }

    public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }

    private  Rank rank;
    private  Suit suit;

    public PlayingCard(Rank rank, Suit suit) {
        this.rank = rank;
        this.suit = suit;
    }

    public Rank getRank() { return rank; }

    public Suit getSuit() { return suit; }


    @Override
    public String toString() { return rank + " of " + suit; }

    @Override
    public int compareTo(ICard o) throws WrongCardTypeException {
        if (o instanceof PlayingCard){
        PlayingCard c = (PlayingCard)o;
        int rankCompare = rank.compareTo(c.rank);
        return rankCompare != 0 ? rankCompare : suit.compareTo(c.suit);
        }
    throw new WrongCardTypeException("Tried to compare "+o.getClass().getCanonicalName()+" to "+ this.getClass().getCanonicalName());
    }

我想知道是否有更简洁的方法可以让我取消instanceof支票?通配符?我不确定。或者instanceof检查好吗?我听说它有'代码味道',例如这是不好的做法。


我的IDeck界面有类似的(?)问题:

public interface IDeck<T extends ICard> extends Comparable<T>, Collection<T>{
    public ArrayList<T> getDeck();
    public void setDeck(Set<T> newDeck);
}

在实现此目的的类中,我的compareTo方法接受ICard类型的参数,但我想比较从IDeck继承的decks。

3 个答案:

答案 0 :(得分:3)

您可以使用绑定使ICard接口具有通用性,因此任何泛型类型参数本身必须是ICard

public interface ICard<T extends ICard<T>>  extends Comparable<T>{

然后,您可以在PlayingCard类的ICard界面中指定PlayingCard

public class PlayingCard implements ICard<PlayingCard> {

答案 1 :(得分:2)

我想你想要

public interface ICard<T> extends Comparable<T>{

  public abstract String toString();

  public abstract int compareTo(T o) throws WrongCardTypeException;

}

(请注意ICard<T>

然后PlayingCard implements ICard<PlayingCard>

也就是说,这个接口在Comparable接口上没有任何内容,因为toString()已经可用于所有Java对象,并且尝试要求它将不起作用。

答案 2 :(得分:1)

您需要“重新指定”T,请尝试:

public interface ICard<T> extends Comparable<T>