[英]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.