java 创建实例的方法,Java调用方法而不创建实例

本文探讨了一位程序员在Java中尝试从一个类调用另一个类的方法时遇到的问题。原来的问题在于如何在多个游戏会话同时运行的情况下避免每次创建新实例时初始化静态ArrayList。解决方案提到,不使用静态方法,而是通过实例化对象来共享数据。测试用例展示了如何在Player类中添加并更新PoliticianCard类的卡片。
摘要由CSDN通过智能技术生成

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值