问题描述
如果这个问题对普通的Java程序员来说很愚蠢,请原谅,但我对此问题感到困惑.我想从类DrawCard(Player player)
中的类PoliticCard
调用方法getPoliticCards()
.起初,我在PoliticCard
中使用了static arraylist
,所以我没有问题,但是我不得不更改它,因为我应该能够同时运行游戏的多个会话.
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<Color> politicCards;
public Player(int id){
this.setId(id);
ArrayList<Color> array=new ArrayList<Color>();
setPoliticCards(array);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ArrayList<Color> getPoliticCards() {
return politicCards;
}
public void setPoliticCards(ArrayList<Color> politicCards) {
this.politicCards = politicCards;
}
}
public class PoliticCard {
private ArrayList<Color> politicCards;
public PoliticCard(){
setPoliticCards(new ArrayList<Color>());
politicCards.add(Color.BLACK);
politicCards.add(Color.PURPLE);
}
public ArrayList<Color> getPoliticCards() {
return politicCards;
}
public void setPoliticCards(ArrayList<Color> 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.
这篇关于Java调用方法而不创建实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!