Static Fields and Methods
时间:2010-09-13 来源:露初晞
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.
class Employee
{
. . .
private int id;
private static int nextId = 1;
}
Even if there are no employee objects, the static field nextId is present. It belongs to the class, not to any individual object.
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 Math object would have its own copy of PI.
Static Methods
Static methods are methods that do not operate on objects. For example, the pow method of the Math class is a static method. The expression:
Math.pow(x, a)
computes the power xa. It does not use any Math object to carry out its task. In other words, it has no implicit parameter.
Because static methods don't operate on objects, you cannot access instance fields from a static method. But static methods can access the static fields in their class. Here is an example of such a static method:
public static int getNextId(){ return nextId; // returns static field}
To call this method, you supply the name of the class:
int n = Employee.getNextId();
Could you have omitted the keyword static for this method? Yes, but then you would need to have an object reference of type Employee to invoke the method.
You use static methods in two situations:
-
When a method doesn't need to access the object state because all needed parameters are supplied as explicit parameters (example: Math.pow)
-
When a method only needs to access static fields of the class (example: Employee.getNextId)
Method Parameters
Here is a summary of what you can and cannot do with method parameters in the Java programming language:
-
A method cannot modify a parameter of primitive type (that is, numbers or Boolean values).
-
A method can change the state of an object parameter.
-
A method cannot make an object parameter refer to a new object.