静态变量
问题描述:
我工作的一个典型的家庭作业程序,并不能为我的生命弄清楚为什么我的超类中的静态变量的反应方式是这样..静态变量
的程序是一个银行帐户,我创建了超类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
答
没有什么不对您的代码,因为你是在单线程模式创建帐户。 你下面的代码工作绝对没问题:
abstract class Account
{
private double balance;
private int accountId;
private static int lastAssignedNumber = 1000;
private String accountType;
public Account (double q_balance, String q_accountType)
{
balance = q_balance;
accountType = q_accountType;
accountId = ++lastAssignedNumber;
}
public int getAccountID()
{
return accountId;
}
}
class CreditAccount extends Account
{
public CreditAccount(double balance)
{
super(balance, "Creditaccount");
}
}
class SavingsAccount extends Account
{
public SavingsAccount(double balance)
{
super(balance, "Savingsaccount");
}
}
public class AccountLedger
{
public static void main(String st[])
{
Account ac[] = new Account[7];
ac[0] = new SavingsAccount(0); //1001
ac[1] = new CreditAccount(0); //1002
ac[2] = new CreditAccount(0); //1003
ac[3] = new SavingsAccount(0); //1004
ac[4] = new CreditAccount(0); //1005
ac[5] = new CreditAccount(0); //1006
ac[6] = new SavingsAccount(0); //1007
for (int i = 0 ; i < ac.length ; i++)
{
System.out.println(ac[i].getAccountID());
}
}
}
答
的多和singlethreading的概念坦言完全新的给我,但我试图使既有的AtomicInteger并用完全相同的结果volatile变量。我想这是我的程序结构,基本上是错误的。
该构造是一个BankLogic类,它持有一个CustomerList对象的ArrayList。 Customer对象持有AccountList对象的ArrayList。我放置AtomicInteger对象的位置并不重要,尽管我将它放在BankLogic类中并将它传递给构造函数,但它仍然显示出相同的结果。
猜猜我应该只将帐号ArrayList放入BankLogic类,然后运行一个比较personal-id(将persId变量添加到帐号类)的方法呢?它当然不会像这样一个优雅的解决方案,但我没有看到其他方式。
感谢您的所有答案!
您是否使用多个线程?增量前后运算符不是原子的,因此跨多个线程执行的操作可能会交织并产生意外的结果。 – 2013-02-25 20:44:09
你应该同步这些。 – 2013-02-25 20:46:40
你可以发布你实际创建这些不同帐户的地方,以及你如何检索他们的accountId? – asteri 2013-02-25 20:46:47