java 每次实例化一个新的时,如何在java类中增加一个字段成员
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16716646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to increment a field member in a java class each time a new one is instantiated
提问by ledgeJumper
VERY new to Java, so I am feeling like a child right now. The joys of learning a new language I guess.
对 Java 非常陌生,所以我现在感觉像个孩子。我猜是学习一门新语言的乐趣。
Here is my Invoice Class:
这是我的发票类:
public class Invoice {
//member inits
private int numberOfInvoices = 0;
private String companyName;
private double amountDue;
private String chargeDate;
private static int invoiceNumber = 0;
//constructor
public Invoice(String _companyName, double _amountDue, String _chargeDate)
{
numberOfInvoices++;
companyName = _companyName;
amountDue = _amountDue;
chargeDate = _chargeDate;
invoiceNumber = numberOfInvoices;
}
//getters
public String getCompanyName()
{
return companyName;
}
public double getAmountDue()
{
return amountDue;
}
public String getChargeDate()
{
return chargeDate;
}
public int getInvoiceNumber()
{
invoiceNumber = numberOfInvoices + 1;
return invoiceNumber;
}
//setters
public void setCompanyName(String _companyName)
{
companyName = _companyName;
}
public void setAmountDue(double _amountDue)
{
amountDue = _amountDue;
}
public void setChargeDate(String _chargeDate)
{
chargeDate = _chargeDate;
}
//helpers
public int incrementInvoices()
{
return numberOfInvoices++;
}
}
And here is the main method where I am trying to create three of these invoices, but increment the invoice number each time a new one is created.
这是我尝试创建其中三张发票的主要方法,但每次创建新发票时都会增加发票编号。
public class InvoiceCreator {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Invoice invoice1 = new Invoice("Amazing Software", 5000.00, "January 18, 2009");
System.out.println(invoice1);
Invoice invoice2 = new Invoice("Best Programs", 4000.00, "February 18, 2009");
System.out.println(invoice2);
Invoice invoice3 = new Invoice("Champion Code", 3000.00, "March 18, 2009");
System.out.println(invoice3);
}
}
I'm also new to the IDE (netbeans), but through debugging and looking at each of the classes I created, all the fields are being initialized correctly, but the invoiceNumber = 1 on every one of them.
我也是 IDE (netbeans) 的新手,但是通过调试和查看我创建的每个类,所有字段都被正确初始化,但是每个字段的 invoiceNumber = 1。
What am I doing incorrectly here?
我在这里做错了什么?
采纳答案by waldol1
You need to use a static field to generate incremental invoice numbers, not store the individual invoice numbers.
您需要使用静态字段来生成增量发票编号,而不是存储单个发票编号。
Try this:
试试这个:
public class Invoice {
//member inits
private static int nextInvoiceNumber = 0;
private String companyName;
private double amountDue;
private String chargeDate;
private int invoiceNumber = 0;
//constructor
public Invoice(String _companyName, double _amountDue, String _chargeDate)
{
invoiceNumber = nextInvoiceNumber;
nextInvoiceNumber++;
companyName = _companyName;
amountDue = _amountDue;
chargeDate = _chargeDate;
}
....
回答by Andy Thomas
Declare numberOfInvoices to be static
, so that there is a single value for the entire class, rather than a separate value for each instance.
将 numberOfInvoices 声明为static
,以便整个类只有一个值,而不是每个实例都有一个单独的值。
private static int numberOfInvoices = 0;
回答by Aleks G
You declared invoiceNumber
as static, but numberOfInvoices
is not static. In your constructor you are incrementing the number of invoices - which, being non-static, is initialised to 0 every time you create an instance of it. Then you assign this value to your invoice number.
您声明invoiceNumber
为静态,但numberOfInvoices
不是静态的。在您的构造函数中,您正在增加发票的数量 - 这是非静态的,每次创建它的实例时都会初始化为 0。然后您将此值分配给您的发票编号。
The simple fix for your case is to declare the numberOfInvoices
as static and invoiceNumber
as non static:
您的情况的简单修复是将其声明numberOfInvoices
为静态和invoiceNumber
非静态:
private static int numberOfInvoices = 0;
private int invoiceNumber;
then you'll get the desired behaviour.
那么您将获得所需的行为。
At the same time, it's worth noting that this implementation is ok for the purpose of learning the language, however it will not work for a production system, because the number will still be reset to 0 when the application exits and is restarted. In a production system, you would want to keep this number in a database or external file somewhere. You would then need to ensure that it's incremented in a thread-safe manner. In a production system, your logic would be something like this:
同时值得注意的是,这个实现对于学习语言来说是可以的,但是它不适用于生产系统,因为当应用程序退出和重新启动时,数字仍然会被重置为0。在生产系统中,您可能希望将此编号保存在某个数据库或外部文件中。然后,您需要确保它以线程安全的方式递增。在生产系统中,您的逻辑将是这样的:
private int invoiceNumber;
private Object sync;
public Invoice(...) {
synchronised(sync) {
invoiceNumber = loadLastInvoiceNumberFromStorage();
invoiceNumber++;
writeLastInvoiceNumberFromStorage(invoiceNumber);
}
...
}
回答by Moritz Petersen
numberOfInvoices
should be static. invoiceNumber
should not be static. And you should synchronize the accessto this field. See also: What is the best way to increase number of locks?
numberOfInvoices
应该是静态的。invoiceNumber
不应该是静态的。并且您应该同步对该字段的访问。另请参阅:增加锁数量的最佳方法是什么?
回答by Dave Newton
numberOfInvoices
isn't the static member.
numberOfInvoices
不是静态成员。
You currently increment an instanceproperty and set it to the static property.
您当前增加了一个实例属性并将其设置为静态属性。
I suspect you want the opposite.
我怀疑你想要相反的。
回答by Mena
You could use a static field numberOfInvoices
in your class, and increment it in the constructor.
Then you could have a static getter for the field.
您可以numberOfInvoices
在类中使用静态字段,并在构造函数中增加它。然后,您可以为该领域设置一个静态吸气剂。
回答by Adarsh
numberOfInvoices will always be 0 when a new object is created. So, everytime you increment it and assign it to invoiceNumber, invoiceNumber gets the value 1. Instead, why dont you directly increment invoiceNumber .
创建新对象时,numberOfInvoices 将始终为 0。因此,每次增加它并将其分配给 invoiceNumber 时, invoiceNumber 都会获得值 1。相反,为什么不直接增加 invoiceNumber 。
回答by stinepike
use
利用
private static int numberOfInvoices = 0;
Reason:
原因:
Static variables are related to class while nonstatic variables are related to object. As in this case you are storing the count of the object of the class so this is related to class. Thus you have to store it as static variable ( also called class variable)
静态变量与类相关,而非静态变量与对象相关。在这种情况下,您正在存储类对象的计数,因此这与类有关。因此您必须将其存储为静态变量(也称为类变量)
For more details see here
有关更多详细信息,请参见此处
回答by Julien Bodin
You should declare your numberOfInvoices member as a static member :
您应该将 numberOfInvoices 成员声明为静态成员:
private static int numberOfInvoices = 0;
This way all Invoice instance will share this member. If you don't declare it each Invoice instance will have their own value.
这样所有的 Invoice 实例都将共享这个成员。如果您不声明它,则每个 Invoice 实例都将具有自己的值。