Java Reference
In-Depth Information
3.6. Marking Methods and Classes
final
Marking a method
final
means that no extended class can override the
method to change its behavior. In other words, this is the
final
version of
that method. Entire classes can also be marked
final
:
final class NoExtending {
// ...
}
A class marked
final
cannot be extended by any other class, and all the
methods of a final class are themselves effectively
final
.
Final classes and methods can improve security. If a class is
final
,
nobody can declare a class that extends it, and therefore nobody can vi-
olate its contract. If a method is
final
, you can rely on its implementation
details (unless it invokes non-
final
methods, of course). You could use
final
, for example, on a
validatePassword
method to ensure that it does
what it is advertised to do instead of being overridden to always return
TRue
. Or you can mark as
final
the class that contains the method so that
it can never be extended to confuse the implementation of
validatePass-
word
.
Marking a method or class
final
is a serious restriction on the use of the
class. If you make a method
final
, you should really intend that its beha-
vior be completely fixed. You restrict the flexibility of your class for other
programmers who might want to use it as a base from which to add func-
tionality to their code. Marking an entire class
final
prevents anyone else
from extending your class, limiting its usefulness to others. If you make
anything
final
, be sure that you want to create these restrictions.
In many cases, you can achieve the security of marking a whole class
final
by leaving the class extensible and instead marking each method
in the class as
final
. In this way, you can rely on the behavior of those
methods while still allowing extensions that can add functionality without