[英]Why does every object of this class have the same value for its members?
I'm writting an application which should be extremely simple but it keeps using the last set values for name
and boxesSold
for everything. 我正在编写一个应用程序,该应用程序应该非常简单,但它始终使用
name
和boxesSold
的最后设置值来进行所有操作。 Here's a minimal example: 这是一个最小的示例:
public class BandBoosterDriver
{
public static void main (String[] args)
{
BandBooster booster1 = new BandBooster("First");
BandBooster booster2 = new BandBooster("Second");
booster2.updateSales(2);
System.out.println(booster1.toString());
System.out.println(booster2.toString());
}
}
and here is the problem class: 这是问题类别:
public class BandBooster
{
private static String name;
private static int boxesSold;
public BandBooster(String booster)
{
name = booster;
boxesSold = 0;
}
public static String getName()
{
return name;
}
public static void updateSales(int numBoxesSold)
{
boxesSold = boxesSold + numBoxesSold;
}
public String toString()
{
return (name + ":" + " " + boxesSold + " boxes");
}
}
This produces 这产生
Second: 2 boxes
Second: 2 boxes
But I would expect 但是我希望
First: 0 boxes
Second: 2 boxes
How can I get it to work the way I expect it to? 如何使它按我期望的方式工作?
remove the static keyword. 删除static关键字。 static will indicate your program to use single memory address for this field , and avoid allocating dedicated memory for this field everytime you create an instance of BandBooster.
static将指示您的程序对该字段使用单个内存地址,并且避免每次创建BandBooster实例时都为此字段分配专用内存。
因为它没有任何实例成员,所以只有静态成员。
Statically created variables are unique to the class and shared by all instances of it. 静态创建的变量对于该类是唯一的,并且由其所有实例共享。 What you are seeing is what's supposed to happen.
您所看到的是应该发生的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.