In your example you are not actually setting the name of the player to John you are creating an object called John.
To fix this declare a field inside your Player
class:
public class Player {
String name;
public Player(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now you can create as many players as you want and name them:
Player player = new Player("John");
When you want to get a player's name, just call the getName()
function.
When you want to set a player's name, just call the setName()
method.
To print the players name on the console use this:
System.out.println(player.getName());
Or you can override the toString()
method of Player
to offer a textual representation of the object, in this case only a player's name:
@Override
public String toString() {
return "Player[name=" + name + "]";
}
Then, you can use:
System.out.println(player); // toString() is called if player != null