Documentation

The Java™ Tutorials
Hide TOC
Understanding Class Members理解类成员
Trail: Learning the Java Language
Lesson: Classes and Objects
Section: More on Classes

Understanding Class Members理解类成员

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关键字来创建属于类的字段和方法,而不是属于类的实例。

Class Variables类变量

When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables.当从同一个类蓝图创建多个对象时,每个对象都有各自不同的实例变量副本。In the case of the Bicycle class, the instance variables are cadence, gear, and speed.对于Bicycle类,实例变量是cadencegearspeedEach Bicycle object has its own values for these variables, stored in different memory locations.每个Bicycle对象都有自己的变量值,存储在不同的内存位置。

Sometimes, you want to have variables that are common to all objects.有时,您希望拥有对所有对象通用的变量。This is accomplished with the static modifier.这是通过static修饰符完成的。Fields that have the static modifier in their declaration are called static fields or class variables.声明中包含static修饰符的字段称为静态字段类变量They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory.它们与类相关联,而不是与任何对象相关联。类的每个实例都共享一个类变量,该变量位于内存中的一个固定位置。Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.任何对象都可以更改类变量的值,但也可以在不创建类实例的情况下操作类变量。

For example, suppose you want to create a number of Bicycle objects and assign each a serial number, beginning with 1 for the first object.例如,假设要创建多个Bicycle对象,并为每个对象指定一个序列号,第一个对象从1开始。This ID number is unique to each object and is therefore an instance variable.此ID号对于每个对象都是唯一的,因此是一个实例变量。At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one.同时,您需要一个字段来跟踪已创建的Bicycle对象的数量,以便知道要为下一个对象指定的ID。Such a field is not related to any individual object, but to the class as a whole.这样的字段与任何单个对象无关,而是与类作为一个整体相关。For this you need a class variable, numberOfBicycles, as follows:为此,您需要一个类变量numberOfBicycles,如下所示:

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;
        ...
}

Class variables are referenced by the class name itself, as in类变量由类名本身引用,如中所示

Bicycle.numberOfBicycles

This makes it clear that they are class variables.这表明它们是类变量。


Note: You can also refer to static fields with an object reference like还可以使用对象引用引用静态字段,如
myBike.numberOfBicycles
but this is discouraged because it does not make it clear that they are class variables.但这是不鼓励的,因为它没有明确说明它们是类变量。

You can use the Bicycle constructor to set the id instance variable and increment the numberOfBicycles class variable:您可以使用Bicycle构造函数设置id实例变量并递增numberOfBicycles类变量:

public class Bicycle {
        
    private int cadence;
    private int gear;
    private int speed;
    private int id;
    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;
    }
        ...
}

Class Methods类方法

The Java programming language supports static methods as well as static variables.Java编程语言支持静态方法和静态变量。Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in静态方法的声明中包含static修饰符,应该使用类名调用,而无需创建类的实例,如中所示

ClassName.methodName(args)

Note: You can also refer to static methods with an object reference like还可以使用对象引用引用静态方法,如
instanceName.methodName(args)
but this is discouraged because it does not make it clear that they are class methods.但这是不鼓励的,因为它没有明确说明它们是类方法。

A common use for static methods is to access static fields.静态方法的一个常见用途是访问静态字段。For example, we could add a static method to the Bicycle class to access the numberOfBicycles static field:例如,我们可以向Bicycle类添加一个静态方法来访问numberOfBicycles静态字段:

public static int getNumberOfBicycles() {
    return numberOfBicycles;
}

Not all combinations of instance and class variables and methods are allowed:并非所有实例和类变量及方法的组合都是允许的:

Constants常数

The static modifier, in combination with the final modifier, is also used to define constants.static修饰符与finally修饰符一起还用于定义常量。The final modifier indicates that the value of this field cannot change.final修饰符指示此字段的值不能更改。

For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):例如,以下变量声明定义了一个名为PI的常量,其值是π(圆的周长与其直径之比)的近似值:

static final double PI = 3.141592653589793;

Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so.以这种方式定义的常量不能被重新分配,如果您的程序试图这样做,这将是一个编译时错误。By convention, the names of constant values are spelled in uppercase letters.按照惯例,常量值的名称用大写字母拼写。If the name is composed of more than one word, the words are separated by an underscore (_).如果名称由一个以上的单词组成,则这些单词之间用下划线(_)分隔。


Note: If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value.如果原语类型或字符串被定义为常量,并且该值在编译时是已知的,则编译器会用其值替换代码中所有地方的常量名称。This is called a compile-time constant.这称为编译时常量If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.如果外部世界中常量的值发生变化(例如,如果法律规定pi实际上应为3.975),则需要重新编译使用此常量的任何类以获得当前值。

The Bicycle ClassBicycle

After all the modifications made in this section, the Bicycle class is now:在本节中进行所有修改后,Bicycle类现在为:

public class Bicycle {
        
    private int cadence;
    private int gear;
    private int speed;
        
    private int id;
    
    private static int numberOfBicycles = 0;

        
    public Bicycle(int startCadence,
                   int startSpeed,
                   int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;

        id = ++numberOfBicycles;
    }

    public int getID() {
        return id;
    }

    public static int getNumberOfBicycles() {
        return numberOfBicycles;
    }

    public int getCadence() {
        return cadence;
    }
        
    public void setCadence(int newValue) {
        cadence = newValue;
    }
        
    public int getGear(){
        return gear;
    }
        
    public void setGear(int newValue) {
        gear = newValue;
    }
        
    public int getSpeed() {
        return speed;
    }
        
    public void applyBrake(int decrement) {
        speed -= decrement;
    }
        
    public void speedUp(int increment) {
        speed += increment;
    }
}

Previous page: Controlling Access to Members of a Class
Next page: Initializing Fields