zahra
zahra

Reputation: 31

how to call object of one class that has been created in another class?

I'm just starter at coding . I wanna write a game code and I have a problem : I want to call an object of one class in another class but there is a eror with my code.

I have three classes : Game , Player , commandReader.

class Player :

public class Player{

   public void moveUp(){
   ...
   }
}

I had been created an object of class Player in Game class:

public class Game{

   public Player player;

   private Game(){
      player = new Player;
   }

   // methods omitted
}

I want to call object "player" in another class named commandReader :

public class commandReader{

   public readCommand(String command){
      if(command == "Up"){
         player.moveUp();
      }
   }
}

but there is a error when I run the code. the object player is unknown for class commandReader. I should mention that I don't wanna create another object of class Player in class commandReader and I just use the one that has been created in the Game class. how should I call that?

Upvotes: 0

Views: 278

Answers (3)

MattyG
MattyG

Reputation: 66

The commandReader class doesn't show a game object anywhere.

public class commandReader{

   Game myGame = new Game();
   public readCommand(String command){
      if(command == "Up"){
      myGame.player.moveUp();
  }

} }

Upvotes: 0

rpasianotto
rpasianotto

Reputation: 1413

Well, there are some errors.

In the class Game you have to declare the variable player in that way:

public Player player;

Then in the constructor of the Game class

player = new Player();

Which can't be call because in the Player class there isn't the constructor

class Player{

  //CONSTRUCTOR (initialize the object)
  public Player(){

  }

  [...]

}

After that adjustment you can call the player from commandReader with

Game.player.moveUp();//Only if it's a static variable

Hope you understand something new.

[UPDATE]

Right you also don't add the constructor in the Game class, because it must be

public Game(){
  [...]
}

And not

private Game(){
  [...]
}

Then in the commandReader you have to create a Game object by

Game game = new Game();

And then for the player

game.player.moveUp();

Upvotes: 0

Harry Blargle
Harry Blargle

Reputation: 426

You would have to pass a reference to the game class into the constructor of commandReader.

Game game;

public commandReader(Game game)
{
    this.game = game;
}

And then you can call

game.player.moveUp();

Upvotes: 1

Related Questions