带有类型参数的Java类

问题描述 投票:1回答:1

我在Java类中使用类型参数时遇到麻烦。我有一个超类叫做Game

public abstract class Game<T extends Player> implements Serializable {
    public Game(GameEnum game, Player player1, T player2) {
        this.timer = new Timer();
        this.game = game;
        this.player1 = player1;
        this.player1.setPlayer1();
        this.player2 = player2;
   }
}

然后是我的班级对其进行扩展

public abstract class OtherGame<T extends Player> extends Game<T> {
    public OtherGame(GameEnum game, Player player1, T player2) {
        super(game, player1, player2);
    }
}

然后是扩展了类OtherGame的类ChessGame

public class ChessGame<T extends Player> extends OtherGame<T> {
    public ChessGame(Player player) {
        super(GameEnum.CHESS, player, new ChessComputer());

        //Here is the Error that the Constructor with the Param. ChessComputer
        //does not exist and i can cast the ChessComputer to T.

        ((Computer) super.player2).setInput(this.chessboard);
        this.playerFile = new File(CHESSGAME, String.format("%s vs. Computer%s", super.player1, FILEEXT));
        this.comFile = new File(CHESSGAME, super.player1.hashCode() + "");
        this.gameMenu();
    }
}

现在我也有一些PlayerClasses

public class Player implements Serializable {
    public Player(String name, boolean player1) {
        this.name = name;
        this.player1 = player1;
    }
}

还有我的扩展Player类的Computerclass

public abstract class Computer extends Player {
    public Computer() {
        super("Computer", false);
    }
}

而且我有一个ChessComputer类,它扩展了Computerclass类

public class ChessComputer extends Computer {
    public ChessComputer() {
        super();
    }
}

然后我有了一个类,该类如下调用ChessGameclass的构造方法:

new ChessGame<ChessComputer>(this.player);
//Here is no error

为什么会出现错误,指出没有这样的构造函数,因为我认为如果我使用TypeVariable(例如T),我可以为该构造函数提供我将扩展的子类的任何子类。我还用Typeargument ChessComputer来称呼ChessGame构造函数,我认为其中的“类”为ChessComputer类。我对Typearguments及其在Java中的工作方式了解得很少,但显然还不够。

对不起,如果我不使用正确的词来形容它,那是因为英语不是我的母语。

java subclass extends generic-type-argument
1个回答
0
投票

这里,类派生的类对的结构具有通用类型约束:

© www.soinside.com 2019 - 2024. All rights reserved.