[英]calling a class inside another class constructor? java
I'm not understanding what other people have done for this. 我不了解其他人为此做了什么。 And for some reason there seems to be lack of education on this subject.
由于某种原因,似乎缺乏关于该主题的教育。 But I would think for java it would be very important being that its sole purpose is the use of multiple classes.
但是我认为对于Java来说,它的唯一目的是使用多个类将非常重要。 My question is, how do I build the "player class constructor" in a fashion that encapsulates the instance of class board?
我的问题是,如何以封装类板实例的方式构建“玩家类构造函数”?
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");
}
}
This is what I have, am I even doing this right? 这就是我所拥有的,我什至在这样做对吗?
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 )
{
}
}
You need to add a field, eg board
, to your Player
class. 您需要在
Player
类中添加一个字段,例如board
。 Then, in the constructor, do this: 然后,在构造函数中,执行以下操作:
this.board = board;
No, you are thinking about it wrong. 不,您在想错了。
Player
can exist and function without Board
. Player
无需Board
即可生存并发挥作用。 Surely, he can't play without Board
but he can do other stuff, like looks for a Board
to play on. 当然,他离不开
Board
但他可以做其他事情,例如寻找Board
。 Meanwhile Board
is inanimate object, which sole purpose is to provide a place for Player
to play on. 同时,
Board
是无生命的对象,其唯一目的是为Player
提供玩耍的场所。 Board
does not care which Player
plays on it though. Board
并不关心哪个Player
在玩。
So general rule when creating constructor is to pass the objects that are needed for the object to function as parameters, not the other way around. 因此,创建构造函数时的一般规则是传递对象以用作参数,而不是相反。 For example you should be passing
Car
inside Driver
constructor, but you should not pass Driver
into Car
constructor, since car does not need any particular Driver
to function as a Car. 例如,您应该在
Driver
构造函数内部传递Car
,但不应将Driver
传递给Car
构造函数,因为car不需要任何特定的Driver
即可充当Car。 Meanwhile Driver needs a Car to function as a Driver. 同时,驾驶员需要汽车来充当驾驶员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.