Please excuse me if this question looks dumb for a regular java programmer but i'm stuck with this problem.
I want to call the method getPoliticCards() from the class PoliticCard in the class DrawCard(Player player). At first i used a static arraylist in PoliticCard so i had no problems, but i had to change it because i'm supposed to be able to run several sessions of the game at the same time.
public enum Color {
BLACK, PURPLE
}
public class Player {
private int id;
private ArrayList politicCards;
public Player(int id){
this.setId(id);
ArrayList array=new ArrayList();
setPoliticCards(array);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ArrayList getPoliticCards() {
return politicCards;
}
public void setPoliticCards(ArrayList politicCards) {
this.politicCards = politicCards;
}
}
public class PoliticCard {
private ArrayList politicCards;
public PoliticCard(){
setPoliticCards(new ArrayList());
politicCards.add(Color.BLACK);
politicCards.add(Color.PURPLE);
}
public ArrayList getPoliticCards() {
return politicCards;
}
public void setPoliticCards(ArrayList politicCards) {
this.politicCards = politicCards;
}
}
public class DrawPoliticCard {
public DrawPoliticCard(Player player){
PoliticCard politicCard = new PoliticCard();//I know that to
//call a method from another class you should create an instance,
//but isn't *new PoliticCard();* creating a new arraylist in PoliticCard()?,
//what i want is to create the arraylist only once (like it's written in the test below)
//and then use the same updated arraylist each time i use this constructor
player.getPoliticCards().add(politicCard.getPoliticCards().get(0));
politicCard.getPoliticCards().remove(0);
}
}
public class ModelPlayerTest {
@Test
public void testDrawCard() {
Player player = new Player(1);
new PoliticCard();
new DrawPoliticCard(player);
assertNotNull(player.getPoliticCards().get(0));
}
}
解决方案
The only way to invoke a method from a class without using a real instance of it is by invoking a static method.