Movatterモバイル変換


[0]ホーム

URL:


Documentation

The Java™ Tutorials
Interfaces and Inheritance
Interfaces
Defining an Interface
Implementing an Interface
Using an Interface as a Type
Evolving Interfaces
Default Methods
Summary of Interfaces
Questions and Exercises
Inheritance
Multiple Inheritance of State, Implementation, and Type
Overriding and Hiding Methods
Polymorphism
Hiding Fields
Using the Keyword super
Object as a Superclass
Writing Final Classes and Methods
Abstract Methods and Classes
Summary of Inheritance
Questions and Exercises
Trail: Learning the Java Language
Lesson: Interfaces and Inheritance
Section: Inheritance
Home Page >Learning the Java Language >Interfaces and Inheritance
« Previous • Trail • Next »

The Java Tutorials have been written for 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.
SeeDev.java for updated tutorials taking advantage of the latest releases.
SeeJava Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.
SeeJDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

Writing Final Classes and Methods

You can declare some or all of a class's methodsfinal. You use thefinal keyword in a method declaration to indicate that the method cannot be overridden by subclasses. TheObject class does this—a number of its methods arefinal.

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. For example, you might want to make thegetFirstPlayer method in thisChessAlgorithm class final:

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

Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results.

Note that you can also declare an entire class final. A class that is declared final cannot be subclassed. This is particularly useful, for example, when creating an immutable class like theString class.

« PreviousTrailNext »

About Oracle |Contact Us |Legal Notices |Terms of Use |Your Privacy Rights

Copyright © 1995, 2024 Oracle and/or its affiliates. All rights reserved.

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

[8]ページ先頭

©2009-2025 Movatter.jp