JAVA静态变量
2008-01-05 09:07:21 来源:WEB开发网核心提示:java的静态变量相当于类字段,而不用理解为对象字段,JAVA静态变量,Static Fields and MethodsIn all sample PRograms that you have seen, the main method is tagged with the static modifier. We a
java的静态变量相当于类字段,而不用理解为对象字段。
--------------------------------------------------------------------------------
Static Fields and Methods
In all sample PRograms that you have seen, the main method is tagged with the static modifier. We are now ready to discuss the meaning of this modifier.
Static Fields
If you define a field as static, then there is only one sUCh field per class. In contrast, each object has its own copy of all instance fields. For example, let's suppose we want to assign a unique identification number to each employee. We add an instance field id and a static field nextId to the Employee class:
class Employee
{
. . .
private int id;
private static int nextId = 1;
}
Now, every employee object has its own id field, but there is only one nextId field that is shared among all instances of the class. Let's put it another way. If there are one thousand objects of the Employee class, then there are one thousand instance fields id, one for each object. But there is a single static field nextId. Even if there are no employee objects, the static field nextId is present. It belongs to the class, not to any individual object.
In most object-oriented programming languages, static fields are called class fields. The term "static" is a meaningless holdover from C++.
Let's implement a simple method:
public void setId()
{
id = nextId;
nextId++;
}
Suppose you set the employee identification number for harry:
harry.setId();
Then the id field of harry is set, and the value of the static field nextId is incremented:
harry.id = . . .;
Employee.nextId++;
Constants
Static variables are quite rare. However, static constants are more common. For example, the Math class defines a static constant:
public class Math
{
. . .
public static final double PI = 3.14159265358979323846;
. . .
}
You can access this constant in your programs as Math.PI.
If the keyWord static had been omitted, then PI would have been an instance field of the Math class. That is, you would need an object of the Math class to access PI, and every object would have its own copy of PI.
Another static constant that you have used many times is System.out. It is declared in the System class as:
更多精彩
赞助商链接