In this section, we discuss the use of the static
keyword to create fields and methods that belong to the class, rather than to an instance of the class.
这一部分,我们将讨论关键字static的使用,它用来创建的域和方法隶属于类本身,而不像通常那样隶属于实例。
例如,依据自行车蓝图,生产一系列自行车实体,每辆自行车都要有一个全球唯一序列号:
public class Bicycle {
private int cadence;
private int gear;
private int speed;
// add an instance variable for the object ID
private int id;
// add a class variable for the
// number of Bicycle objects instantiated
private static int numberOfBicycles = 0;
public Bicycle(int startCadence, int startSpeed, int startGear){
gear = startGear;
cadence = startCadence;
speed = startSpeed;
// increment number of Bicycles
// and assign ID number
id = ++numberOfBicycles;
}
// new method to return the ID instance variable
public int getID() {
return id;
}
public static int getNumberOfBicycles() {
return numberOfBicycles;
}
...
}
The
final
modifier indicates that the value of this field cannot change.
关键字final指示该域的值不能改变。
static final double PI = 3.141592653589793;