简体   繁体   中英

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. 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. Then, in the constructor, do this:

this.board = board;

No, you are thinking about it wrong. Player can exist and function without Board . Surely, he can't play without Board but he can do other stuff, like looks for a Board to play on. Meanwhile Board is inanimate object, which sole purpose is to provide a place for Player to play on. Board does not care which Player plays on it though.

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. Meanwhile Driver needs a Car to function as a Driver.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM