简体   繁体   English

从另一个 class object 访问 class 的 object

[英]Accessing an object of a class from another class object

Starting of I want to apologise for my english as I'm not a native speaker.一开始我想为我的英语道歉,因为我不是母语人士。 The title might be a bit off since I was not sure how to phrase it but hopefully it will come through once I show my code.标题可能有点偏离,因为我不知道如何表达它,但希望一旦我展示我的代码,它就会出现。

The problem I'm phasing is I want to use the shop class to handle any purchases while storing the money variable on the player class.我正在逐步解决的问题是我想使用商店 class 来处理任何购买,同时将货币变量存储在播放器 class 上。

Is there any way to access the money integer of the player class without creating an object of the player class in the shop class? Is there any way to access the money integer of the player class without creating an object of the player class in the shop class?

I was thinking about using a static integer to store the data in but from what I've read online its bad practice to use static datatypes.我正在考虑使用 static integer 来存储数据,但是从我在网上阅读的内容来看,使用 static 数据类型是一种不好的做法。

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!");
        }       
     }      
   }
}

So I cut down my code to show you only the essential parts.所以我减少了我的代码,只向你展示基本部分。 What I want to do is access p1:s money variable from the player class from within the Shop class.我想要做的是从商店 class 中的玩家 class 访问 p1:s money 变量。

So far I have been passing the variable when calling it from main.到目前为止,我在从 main 调用它时一直在传递变量。 Is this the only option I have or can it be accessed in any other way?这是我唯一的选择还是可以以任何其他方式访问?

Any help would be much appreciated!任何帮助将非常感激!

I believe the option that follows Object-Oriented Programming principles best is to pass the actual Player in as an argument, instead of just the money.我相信最好遵循面向对象编程原则的选项是将实际的玩家作为参数传入,而不仅仅是金钱。

Basically, passing just the player's money in instead of the player themselves is like just handing your wallet over to the cashier.基本上,只传递玩家的钱而不是玩家自己就像只是将你的钱包交给收银员。 You wouldn't do that, right?你不会那样做的,对吧?

This way, the clerk can ask the customer if they have enough money by calling player.getMoney() , and the customer can tell them the answer.这样,店员可以通过调用player.getMoney()询问客户是否有足够的钱,客户可以告诉他们答案。

After making the purchase, the player can remove the money from their wallet themselves when the clerk asks them to via player.setMoney() .购买后,当店员通过player.setMoney()要求时,玩家可以自己从钱包中取出钱。

Now, you asked in a comment about "passing the actual player as an argument without creating a new object of the player class."现在,您在评论中询问“将实际播放器作为参数传递而不创建播放器 class 的新 object”。 Java passes arguments by value, and all objects' values are simply the address that hold the information for that particular instance. Java 按值传递 arguments,所有对象的值只是保存该特定实例信息的地址。

So for Player p1 in Beta, let's pretend all of p1's information is stored in a block starting at...let's say, address 21343. In this case, the variable p1 only contains that single number, 21343.因此,对于 Beta 版的玩家 p1,假设 p1 的所有信息都存储在一个块中,该块的起始地址是……比如说地址 21343。在这种情况下,变量 p1 仅包含单个数字 21343。

Since Java passes by value, then when you call s1.clerk(Player player) , the player variable will also contain 21343. Since it's editing the items contained at the same address, you've essentially passed on p1 itself instead of creating a new Player.由于 Java 是按值传递的,因此当您调用s1.clerk(Player player)时, player变量也将包含 21343。由于它正在编辑包含在同一地址的项目,因此您实际上传递了p1本身而不是创建一个新的播放器。 In short, the clerk and the main method work with the same object.简而言之,文员和主方法使用相同的object。

The fact that Java passes by value is also why passing just the player's money in doesn't adjust it automatically: The money is an int rather than an object. Java 按值传递的事实也是为什么只传递玩家的钱不会自动调整它的原因:钱是 int 而不是 object。 Since it's an int, when you pass it to the clerk, you're just saying "Hey, clerk, this is the amount of money being worked with."因为它是一个整数,所以当你将它传递给职员时,你只是说“嘿,职员,这是正在处理的金额。” But the clerk has no idea who the money belongs to, so while it can take money, or even give it some, it's essentially just setting it down on the counter, and it's the responsibility of the player to pick it up from there when they're done.但是店员不知道钱是属于谁的,所以虽然可以拿钱,甚至可以给钱,但本质上只是把钱放在柜台上,玩家有责任在柜台上捡到钱。 '重做。 By passing in the player instead, the clerk knows who the money belongs to because it's actually asking the player how much money they have.相反,通过传入玩家,店员知道钱属于谁,因为它实际上是在询问玩家他们有多少钱。

Another potential solution would be to make p1 and s1 static variables in the Beta class.另一种可能的解决方案是在 Beta class 中创建 p1 和 s1 static 变量。 It'd look something like this:它看起来像这样:

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());
    }
}

From there, you'd import the Beta class in Shop , then call Beta.p1 in Shop to access p1 .从那里,您将在Shop中导入Beta class ,然后在Shop中调用Beta.p1以访问p1 Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM