Access members of one class from another class

Abhinav Srivastava :

The code:

import java.util.*;
/*
TicTac Game
__X_|__O_|__X_
__O_|__X_|__O_
  X |  O |  X
*/
public class TicTac{
  public static void main(String[] args) {
    Welcome.greet();
    Game start = new Game();
    start.inputName();
    Welcome.greetPlayer();
    start.show();
  }
}
class Welcome{
  public static void greet(){
    System.out.println("\tTicTac Game By Abhi:");
    System.out.println("\t  __X_|__O_|__X_");
    System.out.println("\t  __O_|__X_|__O_");
    System.out.println("\t    X |  O |  X");
  }
  public static void greetPlayer(){
    Game call = new Game();
    System.out.println("Welcome " + " " + call.x + " and " + call.y + "\n" + "Have Fun!");
  }
}
class Game{
  public String x,y;
  public void inputName(){
    Scanner input = new Scanner(System.in);
    System.out.println("Enter your name Player 1:");
    String Player1 = input.nextLine();
    System.out.println("Enter your name Player 2:");
    String Player2 = input.nextLine();
    x = Player1;
    y = Player2;
  }
  public void show(){
    System.out.println("Hi " + " " + x + " and " + y);
  }
}

When I try to call Welcome.greetPlayer() it gives a null value both times. But whenever try to call start.show it give me values of x and y. I want to access String x and y in welcome class.

Samuel Philipp :

The problem is you are using two different Game objects. The first is created in your main() method, the second in the greetPlayer() method. You are initializing the player names only for the object in the main() method. They are never initialized in the second object.

I assume you want to use only one Game object. One solution would be to pass the Game object to the greetPlayer() method:

public static void main(String[] args) {
    Welcome.greet();
    Game start = new Game();
    start.inputName();
    Welcome.greetPlayer(start);
    start.show();
}
public static void greetPlayer(Game call){
    System.out.println("Welcome " + " " + call.x + " and " + call.y + "\n" + "Have Fun!");
}

Another option would be to pass the names directly to the greetPlayer() method:

public static void main(String[] args) {
    Welcome.greet();
    Game start = new Game();
    start.inputName();
    Welcome.greetPlayer(start.x, start.y);
    start.show();
}
public static void greetPlayer(String player1, String player2){
    System.out.println("Welcome " + " " + player1 + " and " + player2 + "\n" + "Have Fun!");
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=143610&siteId=1