The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Classes and Inheritance

Writing Final Classes and Methods

Final Classes

You can declare that your class is final, that is, that your class cannot be subclassed. You might want to do this for two reasons: (1) to increase system security by preventing system subversion, and (2) for reasons of good object-oriented design. To specify that your class is final, use the keyword final before the class keyword in your class declaration. For example, if you wanted to declare your (perfect) ChessAlgorithm class as final, its declaration should look like this:
final class ChessAlgorithm {
    ...
}
Any subsequent attempts to subclass ChessAlgorithm will result in a compiler error.

Final Methods

If declaring an entire class final is too heavy-handed for your needs, you can declare some or all of the class's methods final instead. Use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this; some of its methods are final, and some are not.

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, instead of making your ChessAlgorithm class final, you might want the nextMove method to be final instead:

class ChessAlgorithm {
    ...
    final void nextMove(ChessPiece pieceMoved,
                        BoardLocation newLocation) {
        ...
    }
    ...
}

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.