Documentation

The Java™ Tutorials
Hide TOC
Writing Final Classes and Methods编写Final类和Final方法
Trail: Learning the Java Language
Lesson: Interfaces and Inheritance
Section: Inheritance

Writing Final Classes and Methods编写Final类和Final方法

You can declare some or all of a class's methods final. 可以将类的部分或全部方法声明为finalYou use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. 在方法声明中使用final关键字表示该方法不能被子类重写。The Object class does this—a number of its methods are final.Object类执行此操作—它的一些方法是final

You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object. 如果一个方法有一个不应更改的实现,并且它对对象的一致性状态至关重要,那么您可能希望将其设置为final。For example, you might want to make the getFirstPlayer method in this ChessAlgorithm class final:例如,您可能希望将此ChessAlgorithm类中的getFirstPlayer方法设置为final

class ChessAlgorithm {
    enum ChessPlayer { WHITE, BLACK }
    ...
final ChessPlayer getFirstPlayer() {
        return ChessPlayer.WHITE;
    }
    ...
}

Methods called from constructors should generally be declared final. 从构造函数调用的方法通常应声明为final。If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results.如果构造函数调用非final方法,子类可能会重新定义该方法,并产生意外或不希望的结果。

Note that you can also declare an entire class final. 请注意,您还可以声明整个类的final。A class that is declared final cannot be subclassed. 声明为final的类不能被子类化。This is particularly useful, for example, when creating an immutable class like the String class.例如,当创建一个不可变的类(如String类)时,这尤其有用。


Previous page: Object as a Superclass
Next page: Abstract Methods and Classes