[英]calling a class inside another class constructor? java
我不了解其他人為此做了什么。 由於某種原因,似乎缺乏關於該主題的教育。 但是我認為對於Java來說,它的唯一目的是使用多個類將非常重要。 我的問題是,如何以封裝類板實例的方式構建“玩家類構造函數”?
public class Driver
{
public static void main(String[] args)
{
//new tic-tac-toe board
Board board = new Board();
//two new players (conputer and human)
Player computer = new Player(board, "X"); //Give computer player access to board and assign as X.
Player human = new Player(board, "O");
}
}
這就是我所擁有的,我什至在這樣做對嗎?
public class Player
{
char player = 'X';
char cpu = 'O';
public static Scanner scan = new Scanner(System.in);
//constructor with board class inside?
public Player(Board board , String inBoard )
{
}
}
您需要在Player
類中添加一個字段,例如board
。 然后,在構造函數中,執行以下操作:
this.board = board;
不,您在想錯了。 Player
無需Board
即可生存並發揮作用。 當然,他離不開Board
但他可以做其他事情,例如尋找Board
。 同時, Board
是無生命的對象,其唯一目的是為Player
提供玩耍的場所。 Board
並不關心哪個Player
在玩。
因此,創建構造函數時的一般規則是傳遞對象以用作參數,而不是相反。 例如,您應該在Driver
構造函數內部傳遞Car
,但不應將Driver
傳遞給Car
構造函數,因為car不需要任何特定的Driver
即可充當Car。 同時,駕駛員需要汽車來充當駕駛員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.