You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shop类中访问Player类对象的money变量(无需创建新对象)

How to Let Shop Access Player's Money Without Static Variables or Creating New Player Objects

Hey there! No need to apologize for your English—your question is totally clear, and the code snippet you shared makes it easy to understand what you're trying to do.

Right now, you're passing the player's money value directly from main to the Shop's clerk method, but there are better, more object-oriented ways to handle this without relying on static variables (which you're right to avoid, since they can lead to messy global state issues). Here are your main options:

Instead of just passing the int value of the player's money, pass the whole Player instance. This lets the Shop interact with the player directly through their public methods, which keeps your code encapsulated and aligned with OOP principles.

First, update your Shop's clerk method to accept a Player parameter:

public class Shop {
    // Assuming these are defined elsewhere in your Shop class
    private int total; // Total cost of the purchase
    private int blue, red, green; // Quantities of items being bought
    private boolean question4;

    public void clerk(Player player) {
        int playerMoney = player.getMoney();
        if (playerMoney >= total) {
            question4 = false;
            System.out.println("Your purchase was successful!");
            
            // Deduct the total cost from the player's money
            // Note: Your current setMoney adds the value, so we pass a negative number
            player.setMoney(-total);
            
            // Add items to inventory (your existing logic)
            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!");
        }
    }
}

Then adjust your main method to pass the Player instance instead of just the money value:

public static void main(String[] args) {
    Player p1 = new Player("Test");
    Shop s1 = new Shop();
    p1.setMoney(100);
    s1.clerk(p1); // Pass the whole player object
}

Why this works better:

  • It keeps the Player's state (like money) encapsulated within the Player class—only the Player should modify its own money, and other classes interact with it through public methods.
  • It lets you easily add more logic later (like deducting money after a purchase) without having to pass extra values between methods.
  • It avoids the problem of "stale" money values (if the player's money changes elsewhere, passing the object ensures the Shop always uses the latest value).

2. Add a dedicated method to Player for purchase checks (Optional)

If you want to keep the Shop even more decoupled from the Player details, you could add a method to Player that checks if they can afford a purchase, and handles deducting the cost:

public class Player {
    private int money;
    private String name;

    // ... existing constructor and methods ...

    public boolean canAfford(int cost) {
        return money >= cost;
    }

    public void deductCost(int cost) {
        if (canAfford(cost)) {
            money -= cost;
        }
    }
}

Then in your Shop's clerk method:

public void clerk(Player player) {
    if (player.canAfford(total)) {
        question4 = false;
        System.out.println("Your purchase was successful!");
        player.deductCost(total);
        // ... inventory logic ...
    } else {
        // ... error message ...
    }
}

This adds another layer of encapsulation, keeping all money-related logic inside the Player class.

What about other approaches?

  • Static variables: As you noted, this is a bad idea here—static variables are shared across all Player instances, so if you have multiple players, they'd all share the same money value, which isn't what you want.
  • Global context: You could create a central Game class that holds references to all Player and Shop instances, and let Shop get the current player from there. But this is overkill for small projects and can introduce unnecessary complexity.

Passing the Player object directly is the simplest, cleanest solution for your use case.

内容的提问来源于stack exchange,提问作者Johan Ekman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:39:04