I'm trying to figure out how the constructors work in the following program. Basically there is a Seeker
class that extends Player
class, and a Game
class that contains Seeker
object, as shown in the code below.
My question is, when the Game
class instantiates mySeeker
using mySeeker = new Seeker( "Sally", this );
does this
invoke the player's constructor? If so, where did it pass on the name of the game? I saw a Game g
in the constructor for Player
, but I can't figure out how the game myGame
(in the main
method) has been passed to the Seeker
.
//Game class
class Game {
Seeker mySeeker;
int gridSize;
Game( int gs ) {
gridSize = gs;
mySeeker = new Seeker( "Sally", this ); //what does 'this' do here? why it does not include the name of the game?
}
void play() {
mySeeker.seek();
}
}
//Player class
abstract class Player {
private Point location;
private String name;
Game game;
Player( Point p, String n, Game g ) {
location = p;
name = n;
game = g;
}
//Seeker class
class Seeker extends Player {
Seeker( String n, Game g ) {
super( new Point( 0, 0 ), n, g ); // seeker starts at 0,0
}
//Main Program
public static void main(String[] args) {
int gridSize = 3; // default value
Game myGame = new Game( gridSize );
myGame.play();
}