从另一个类对象访问一个类的对象

问题描述 投票:0回答:2

由于我不是母语人士,我想为我的英语道歉。标题可能有点过头,因为我不确定该如何说出来,但希望在我显示代码后能够通过。

我要解决的问题是,我想使用shop类来处理所有购买,同时将money变量存储在player类上。

没有任何方法可以在商店类中不创建玩家类的对象的情况下访问玩家类的货币整数吗?

[我当时正在考虑使用静态整数来存储数据,但是从我在线阅读的内容来看,使用静态数据类型是一种不好的做法。

public class Beta {

    public static void main(String[] args) {
        Player p1 = new Player("Test");
        Shop s1 = new Shop();

        p1.setMoney(100);
        s1.clerk(p1.getMoney());

    }
}


public class Player {

    private int money;
    private String name;

    public Player(String name) {
        this.name = name;
    }   
    public int getMoney() {
        return money;
    }
    public void setMoney(int x) {
        this.money +=x;
    }
}

public class Shop {

  private int money;

  public void clerk(int x) {
       this.money = x;
       if (this.money >= total) {
           question4 = false;
           System.out.println("Your purchase was successful!");
           if (blue > 0) {
               this.addInventory("Blue", blue);
           }
           if (red > 0) {
               this.addInventory("Red", red);
           }
           if (green > 0) {
               this.addInventory("Green", green);
           }
        }
        else {
            question4 = false;
            System.out.println("Sorry you cant afford that!");
        }       
     }      
   }
}

因此,我缩减了代码以仅向您显示必要的部分。我想做的是从Shop类中的玩家类访问p1:s money变量。

到目前为止,我从main调用变量时一直在传递变量。这是我唯一的选择,还是可以任何其他方式访问?

任何帮助将不胜感激!

java oop
2个回答
2
投票

我相信,最好地遵循面向对象编程原则的选择是将实际的Player用作参数,而不仅仅是金钱。

[基本上,只转移玩家的钱而不是玩家本人,就像将您的钱包交给收银员一样。您不会那样做,对吧?

这样,业务员可以通过致电player.getMoney()来询问客户他们是否有足够的钱,并且客户可以告诉他们答案。

[购买后,当店员通过player.setMoney()要求玩家将钱从他们的钱包中取出时,就可以了。


0
投票

另一个可能的解决方案是在Beta类中使p1和s1成为静态变量。它看起来像这样:

public class Player
{
    public static Player p1;
    public static Shop s1;

    public static void main(String[] args)
    {
        p1 = new Player("Test");
        s1 = new Shop();

        p1.setMoney(100);
        s1.clerk(p1.getMoney());
    }
}

从此处,您将在Beta中导入Shop类,然后在Beta.p1中调用Shop以访问p1。希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.