Java调用方法而不创建实例 [英] Java Calling A Method without creating an instance

查看:51
本文介绍了Java调用方法而不创建实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这个问题对于普通的 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调用方法而不创建实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆