The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
You can declare some or all of a class's methods final. 可以将类的部分或全部方法声明为final
。You use the 在方法声明中使用final
keyword in a method declaration to indicate that the method cannot be overridden by subclasses. final
关键字表示该方法不能被子类重写。The Object
class does thisa 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
类)时,这尤其有用。