I have Three different classes that all need to use instances of one class. That one class can also make multiple instances of itself, such as player1, player2 etc, and static won’t work for that because it will end up overwriting the old name.
I know that I shouldn’t be using the “new” keyword in the last class, but I don’t know any other way around it.
public class Test{
public static void main(String[] args){
Player player1 = new Player("bob");
Player player2 = new Player("Hank");
System.out.println("Original Name: " + player1.getName());
System.out.println("Original Name 2: " + player2.getName());
Display dis = new Display();
dis.disp();
System.out.println("Changed Name: " + player1.getName());
System.out.println("Changed Name 2: " + player2.getName());
}
}
class Player{
private String pName = "";
public Player(){}
public Player(String name){
pName = name;
}
public void setName(String inName){
pName = inName;
}
public String getName(){
return pName;
}
}
class Display{
public void disp(){
Player player1 = new Player(), player2 = new Player(); //Unneeded
System.out.println("Player name: " + player1.getName());
System.out.println("Player name 2: " + player2.getName());
player1.setName("Joe?");
player2.setName("Billy?");
System.out.println("Player new name: " + player1.getName());
System.out.println("Player new name 2: " + player2.getName());
}
}
It seems you are trying to modify in
Displaythe same instance ofPlayeryou created inTest. If it is indeed the case, you should pass these objects todisp():invoking the method will be:
dis.disp(player1,player2);I must indicate that there is some code smell in here, but it seems like a learning proram, so if it is the case, you shouldn’t be too worried about it at this stage.