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

You can declare some or all of a class's methods final. 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, you might want to make the getFirstPlayer method in this ChessAlgorithm 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 to behave in surprising or undesirable ways.

Note that you can also declare an entire class final — this prevents the class from being subclassed. This may be particularly useful when creating an immutable class like the String class.


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.