我工作的一个典型的家庭作业程序,并不能为我的生命弄清楚为什么我的超类中的静态变量的反应方式是这样..静态变量
的程序是一个银行帐户,我创建了超类Account和两个子类CreditAccount和SavingsAccount。
public abstract class Account {
private double balance;
private int accountId;
**private static int lastAssignedNumber = 1000;** <--- the static int
private String accountType;
public Account (double q_balance, String q_accountType)
{
balance = q_balance;
accountType = q_accountType;
**accountId = ++lastAssignedNumber; <------ counter for new accountId**
}
)
public class CreditAccount extends Account {
public CreditAccount(double balance)
{
super(balance, "Creditaccount");
}
}
public class SavingsAccount extends Account {
public SavingsAccount(double balance)
{
super(balance, "Savingsaccount");
}
}
以前,没有子类当Account是唯一的对象时,计数器工作得很好。但现在,当我创建savingsaccount的一些新的对象和creditaccounts程序的行为很古怪,并按如下返回accountnumbers:
new SavingsAccount(0); // **1001**
new CreditAccount(0); // **1001**
new CreditAccount(0); // **1002**
new SavingsAccount(0); // **1003**
new CreditAccount(0); // **1002**
new CreditAccount(0); // **1004**
new SavingsAccount(0); // **1005**
在神的名字发生了什么事?我错过了什么?不应该这两个子类激发相同的静态变量'lastAssignedNumber'并相应地添加它?
最亲切的问候// Gewra
您是否使用多个线程?增量前后运算符不是原子的,因此跨多个线程执行的操作可能会交织并产生意外的结果。 – 2013-02-25 20:44:09
你应该同步这些。 – 2013-02-25 20:46:40
你可以发布你实际创建这些不同帐户的地方,以及你如何检索他们的accountId? – asteri 2013-02-25 20:46:47