一个对象如何从另一个类中创建的对象调用方法

时间:2013-08-02 19:15:30

标签: java object

我是Java的新手(以及一般的编程),我正在尝试编写一个可以播放Go Fish的程序,但是我很难让一个对象调用另一个对象方法。它尚未完成,但这是我到目前为止所拥有的。 这将被称为开始游戏:

public class StartGame {

public static void start(){
    Deck deck = new Deck(1);
    GoFishHumanPlayer player = new GoFishHumanPlayer();
    GoFishAiPlayer ai = new GoFishAiPlayer();
    player.drawHand();
    ai.drawHand();
    player.turn();
}
}

一个充当游戏套牌的对象。

import java.util.Random;

public class Deck {

private int[] card = new int[14];
private int size;

Random r = new Random();

public Deck(int x){
    size = x;
    card[0] = 4 * size * 13;
    card[1] = 4 * size;
    card[2] = 4 * size;
    card[3] = 4 * size;
    card[4] = 4 * size;
    card[5] = 4 * size;
    card[6] = 4 * size;
    card[7] = 4 * size;
    card[8] = 4 * size;
    card[9] = 4 * size;
    card[10] = 4 * size;
    card[11] = 4 * size;
    card[12] = 4 * size;
    card[13] = 4 * size;}

public int draw(){
    int x = r.nextInt(card[0]) + 1;
    int y = 1;
    while(x>card[y]){
        x -=card[y];
        y++;}
    card[y]--;
    card[0]--;
    return y;}

}

下一节课将由GoFishHumanPlayer和GoFishAiPlayer进行扩展。这些对象将代表玩家。

public class GoFishPlayer {

private int[] hand = new  int[14];
private int pairs;

public void drawHand(){
    for(int x = 0; x < 5; x++){
        int y = deck.draw();//Here's where I get an error "deck cannot be resolved"
        hand[y]++;}
}
}

在GoFishPlayer的第8行,我的IDE说“套牌无法解析”。回到StartGame中,我创建了一个名为deck的对象,但是如何让所有类都可以访问它。

2 个答案:

答案 0 :(得分:4)

无需让所有类都可以访问它,只需在GoFishPlayer的构造函数中传递引用:

public class GoFishPlayer {
  private Deck deck;

  public GoFishPlayer(Deck deck) { this.deck = deck; }
  ...
}

public class StartGame {
  public static void start(){
    Deck deck = new Deck(1);
    GoFishHumanPlayer player = new GoFishHumanPlayer(deck);
    GoFishAiPlayer ai = new GoFishAiPlayer(deck);
    player.drawHand();
    ai.drawHand();
    player.turn();
  }
}

答案 1 :(得分:1)

如果U需要它可以被所有类访问,只需将它传递给构造函数。

public class GoFishPlayer {
private Deck deck;

public GoFishPlayer(Deck deck) { this.deck = deck; }
...
}