如何访问此类中的公共数组

时间:2015-01-09 23:24:11

标签: java

package bagimplementation.ch1;
import bagimplementation.Bag;
import bagimplementation.BagInterface;
import java.util.Arrays;
/**
 * A class that implements a piggy bank by using a bag.
 * @author Jeff Nicholas
 */
public class PiggyBank {
    private BagInterface<Coin> coins;
    public static String[] coinsArray;
    public PiggyBank(){
        coins = new Bag<Coin>();
    }

    public boolean add(Coin aCoin){
        return coins.add(aCoin);
    }

    public Coin remove(){
        return coins.remove();
    }

    public boolean isEmpty(){
        return coins.isEmpty();
    }

}

我想要做的是在具有main方法的测试类中调用变量 coinsArray 。我在测试类中添加了一个print语句,看看我是否有任何数据添加到数组但是printout为null,所以它没有数据。测试类如下

public class PiggyBankExample {

    public static void main(String[] args){
        PiggyBank myBank = new PiggyBank();

        addCoin(new Coin(1, 2010), myBank);
        addCoin(new Coin(5, 2011), myBank);
        addCoin(new Coin(10, 2000), myBank);
        addCoin(new Coin(25, 2012), myBank);

        System.out.println((PiggyBank.coinsArray));
        System.out.println("Removing all the coins:");
        int amountRemoved = 0;

        while(!myBank.isEmpty()){
            Coin removedCoin = myBank.remove();

            System.out.println("Removed a " + removedCoin.getCoinName() + 
                               ".");
            amountRemoved += removedCoin.getCoin();
        }

        System.out.println("All done. Removed " + amountRemoved + " cents.");
    }

    private static void addCoin(Coin aCoin, PiggyBank aBank){
        if(aBank.add(aCoin)){
            System.out.println("Added a " + aCoin.getCoinName() + ".");
        }else{
            System.out.println("Tried to add a " + aCoin.getCoinName() +
                               ", but couldn't");
        }
    }


}

1 个答案:

答案 0 :(得分:1)

那是因为coinsArray在代码中永远不会改变。您只是更改对象中的变量。

您是否尝试在PiggyBank上添加代理方法来访问Bag的toArray方法?

public Object[] toArray() {
    return coins.toArray();
}