【问题标题】:When creating an object from a class, to set a different default value for only the first object created?从类创建对象时,仅为创建的第一个对象设置不同的默认值?
【发布时间】:2021-11-04 16:39:57
【问题描述】:

我正在尝试创建第一个余额较大的帐户,其余所有帐户的默认余额为零。谢谢!

public class Account {
    String address;
    int balance;
    public HashMap<String,Integer> AccountBalanceMap = new HashMap<>();
    boolean firstOnly = true;

public Account(String address) {

    this.address = address;
    this.balance = 0;

    if(firstOnly) {
        AccountBalanceMap.put(address, Integer.MAX_VALUE);
        firstOnly == false;
        System.out.println("first ran");
    } else {
        AccountBalanceMap.put(address, 0);
        System.out.println("second+ ran");
    }
    System.out.println(AccountBalanceMap);
}

}

【问题讨论】:

  • 这需要在静态(类)变量中,而不是在每个实例中创建的实例变量中。不过,IMO 不属于该帐户,而是属于创建帐户的任何东西。

标签: java scope


【解决方案1】:

使用静态成员。 例如

static int nextBalance = 1000;
public Account(String address) {
    this.balance = nextBalance;
    nextBalance = 0;

【讨论】:

    猜你喜欢
    • 2021-08-14
    • 2014-08-05
    • 2013-06-03
    • 2020-04-09
    • 1970-01-01
    • 2015-01-28
    • 2017-11-29
    • 2017-09-30
    • 2016-08-18
    相关资源
    最近更新 更多