java链接两个类在一起

时间:2014-05-02 10:07:27

标签: java

这是一个非常简单的商店java代码,允许用户购买少量商品。

在另一个课程(tamagotchi宠物课程)中,我创建了一个feed()方法,其中一个功能是 - 用于显示在商店中购买的商品的使用情况。

如何链接这两个类以将此功能添加到我的feed()方法?

Shop Class: 

public class Shop {


int balance = 80;
int reward = 100;
int dumplingsMEAL = 1;
int beddingPACK = 1;
int toy = 1;
int dumplingsPrice = 20;
int beddingPrice = 40;
int toyPrice = 10;
int food = 1;
int bedding = 1;
int toys = 1;

public void earnReward () {
    balance = balance + reward;
}

public double getBalance() {
    return balance;
}

public void purchaseDumplings() {
    balance = balance - dumplingsPrice;
    ++food;
}

public void purchaseBedding() {
    balance = balance - beddingPrice;
    ++bedding;
}

public void purchaseToy() {
    balance = balance - toyPrice;
    ++ toys;
}
}

1 个答案:

答案 0 :(得分:1)

tamagotchi pet class中,创建一个新方法Feed(),然后创建Shop类的对象。现在借助引用变量,您可以访问所有Shop类成员函数。

public void feed() {
    Shop shop = new Shop();
    shop.earnReward();
    shop.getBalance();
    shop.purchaseDumplings();
    shop.purchaseToy();
}