Documentation

The Java™ Tutorials
Hide TOC
Initializing Fields初始化字段
Trail: Learning the Java Language
Lesson: Classes and Objects
Section: More on Classes

Initializing Fields初始化字段

As you have seen, you can often provide an initial value for a field in its declaration:如您所见,通常可以在字段声明中为字段提供初始值:

public class BedAndBreakfast {

    // initialize to 10
    public static int capacity = 10;

    // initialize to false
    private boolean full = false;
}

This works well when the initialization value is available and the initialization can be put on one line.当初始化值可用并且可以将初始化放在一行上时,这种方法效果很好。However, this form of initialization has limitations because of its simplicity.但是,由于其简单性,这种形式的初始化具有局限性。If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate.如果初始化需要一些逻辑(例如,错误处理或for循环来填充复杂数组),那么简单的赋值是不够的。Instance variables can be initialized in constructors, where error handling or other logic can be used.实例变量可以在构造函数中初始化,在构造函数中可以使用错误处理或其他逻辑。To provide the same capability for class variables, the Java programming language includes static initialization blocks.为了为类变量提供相同的功能,Java编程语言包括静态初始化块


Note: It is not necessary to declare fields at the beginning of the class definition, although this is the most common practice.不必在类定义的开头声明字段,尽管这是最常见的做法。It is only necessary that they be declared and initialized before they are used.在使用它们之前,只需要声明和初始化它们。

Static Initialization Blocks静态初始化块

A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword.静态初始化块是一个普通的代码块,用大括号{}括起来,前面有static关键字。Here is an example:以下是一个例子:

static {
    // whatever code is needed for initialization goes here
}

A class can have any number of static initialization blocks, and they can appear anywhere in the class body.一个类可以有任意数量的静态初始化块,它们可以出现在类主体中的任何位置。The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.运行时系统保证按照静态初始化块在源代码中出现的顺序调用它们。

There is an alternative to static blocks — you can write a private static method:有一种替代静态块的方法—您可以编写私有静态方法:

class Whatever {
    public static varType myVar = initializeClassVariable();
        
    private static varType initializeClassVariable() {

        // initialization code goes here
    }
}

The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.私有静态方法的优点是,如果需要重新初始化类变量,可以在以后重用它们。

Initializing Instance Members初始化实例成员

Normally, you would put code to initialize an instance variable in a constructor.通常,您会在构造函数中放置初始化实例变量的代码。There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods.使用构造函数初始化实例变量有两种选择:初始化程序块和final方法。

Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:实例变量的初始值设定项块看起来就像静态初始值设定项块,但没有static关键字:

{
    // whatever code is needed for initialization goes here
}

The Java compiler copies initializer blocks into every constructor.Java编译器将初始值设定项块复制到每个构造函数中。Therefore, this approach can be used to share a block of code between multiple constructors.因此,这种方法可以用于在多个构造函数之间共享一块代码。

A final method cannot be overridden in a subclass.不能在子类中重写final方法。This is discussed in the lesson on interfaces and inheritance.这将在接口和继承课程中讨论。Here is an example of using a final method for initializing an instance variable:下面是使用最终方法初始化实例变量的示例:

class Whatever {
    private varType myVar = initializeInstanceVariable();
        
    protected final varType initializeInstanceVariable() {

        // initialization code goes here
    }
}

This is especially useful if subclasses might want to reuse the initialization method.如果子类可能希望重用初始化方法,这一点尤其有用。The method is final because calling non-final methods during instance initialization can cause problems.该方法是final的,因为在实例初始化期间调用非final方法可能会导致问题。


Previous page: Understanding Class Members
Next page: Summary of Creating and Using Classes and Objects