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

Java中如何实现多类间的数值共享,避免类调用时数值丢失?

问题根源

你现在数值丢失的核心原因有两个:

  • 每个类都单独写了main方法作为入口,每次调用Work.main()或者Bank.main()的时候,方法内部都会new一个全新的Bank/Working实例,新实例的属性都是默认初始值0,之前的数值自然就没了
  • 没有统一管理全局共享的状态(现金、银行余额、工作经验),不同类操作的不是同一个对象的属性

最简修改方案

不需要用到序列化,只要把共享对象的实例统一放在入口类Game里维护,所有功能方法都复用同一个实例即可,修改步骤如下:

第一步:删除Work、Bank类里的main方法,替换为普通业务方法

main方法是Java程序的启动入口,一个项目只需要一个入口就够了,我们把业务逻辑抽成普通方法,接收共享的状态对象作为参数:

改后的Work类

import java.util.Scanner;
public class Work extends Working {
    // 接收共享的bank实例、当前工作经验,返回更新后的工作经验
    public int startWork(Banking bank, int currentJobExperience) {
        Scanner input = new Scanner(System.in);
        int process = 0;
        int jobExperience = currentJobExperience;

        while (jobExperience == 0 && process == 0) {
            System.out.println("Welcome! Would you like to apply for a job? Y/N:");
            String response = input.next();

            if (response.equalsIgnoreCase("Y")) {
                jobExperience++;
            }
            else {
                System.out.println("Alright, see you next time!");
                process++;
            }
        }

        while (process == 0) {
            System.out.println("Welcome! Would you like to work? Y/N:");
            String response = input.next();

            if (response.equalsIgnoreCase("Y")) {
                System.out.println("How many hours would you like to work? 1-8:");
                int hours = input.nextInt();

                if (hours >= 1 && hours <= 8) {
                    setHours(hours);
                    setJob(jobExperience);
                    wageCalc();
                    setPaycheck();
                    // 操作的是同一个传入的bank实例,现金会累加
                    bank.setCash(bank.getCash()+getPaycheck());
                    printStatement();
                    jobExperience++;
                    process++;
                }
            }
            else {
                System.out.println("Alright, see you next time!");
                process++;
            }
        }
        return jobExperience;
    }
}

改后的Bank类

import java.util.Scanner;
public class Bank extends Banking {
    // 接收共享的bank实例
    public void startBank(Banking bank) {
        Scanner input = new Scanner(System.in);
        int process = 0;

        System.out.println("Thank you for banking with us. How can we help you?");
        while (process == 0) {
            System.out.println();

            System.out.println("Press 'B' to check your balance.  Press 'D' to deposit money. Press 'W' to withdraw money. Press 'E' to exit.");
            String response = input.next();

            if (response.equalsIgnoreCase("B")) {
                System.out.println("Your bank balance is currently $" + bank.getBalance());
                System.out.println("You currently have $" + bank.getCash() + " in cash.");
            }

            if (response.equalsIgnoreCase("D")) {
                System.out.println("How much would you like to deposit?");
                double amount = input.nextDouble();
                if (bank.getCash() >= amount) {
                    bank.setDeposit(amount);
                    bank.Deposit();
                    bank.setCash(bank.getCash() - amount);
                    System.out.println("You have deposited $" + bank.getDeposit() + ".");
                    System.out.println("Your new balance is $" + bank.getBalance());
                }
                else {
                    System.out.println("Sorry, you do not have enough cash to deposit.");
                }
            }

            if (response.equalsIgnoreCase("W") && bank.getBalance() > 0) {
                System.out.println("How much would you like to withdraw?");
                double amount = input.nextDouble();

                if (amount < bank.getBalance()) {
                    bank.setWithdraw(amount);
                    bank.Withdraw();
                    bank.setCash(bank.getCash() + amount);
                    System.out.println("You have withdrawn $" + bank.getWithdraw() + ".");
                    System.out.println("Your new balance is $" + bank.getBalance());
                }

                else {
                    System.out.println("You do not have sufficient funds to withdraw");
                    System.out.println("Your current balance is $" + bank.getBalance());
                }
            }

            else if (response.equalsIgnoreCase("W") && bank.getBalance() <= 0) {
                System.out.println("You do not have sufficient funds to withdraw");
            }

            if (response.equalsIgnoreCase("E")) {
                process = 2;
                System.out.println("Goodbye!");
            }
        }
    }
}

第二步:修改Game类,统一维护全局共享实例

把需要共享的Banking实例、工作经验都放在Game里管理,每次调用功能方法都传入同一个实例:

import java.util.Scanner;
public class Game {
   public static void main(String[] args) {
        Work work = new Work();
        Bank bank = new Bank();
        // 全局唯一的Banking实例,所有操作都用这一个
        Banking globalBank = new Banking();
        // 全局维护工作经验
        int globalJobExperience = 0;
        Scanner input = new Scanner(System.in);
        int process = 0;
        while (process == 0) {
            System.out.println("What would you like to do?");
            System.out.println("1) Go to the Bank");
            System.out.println("2) Go to Office Building");
            System.out.println("3) Exit Game");
            int response = input.nextInt();
            if (response == 1) {
                // 传入全局实例,操作的都是同一个对象的数值
                bank.startBank(globalBank);
            }
            if (response == 2) {
                // 传入全局实例,更新工作经验
                globalJobExperience = work.startWork(globalBank, globalJobExperience);
            }
            if (response == 3) {
                process++;
            }
        }
    }
}

第三步:原有Working、Banking类无需修改,直接使用即可

修改后所有现金、余额、工作经验都是在同一个实例上操作,不会再出现数值丢失的问题。如果后续需要加存档功能,再把全局的globalBank和globalJobExperience序列化存到本地文件即可,当前阶段不需要用到序列化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 10:24:03