Java Reference
In-Depth Information
Creating a Final Class
All of the classes in the inheritance hierarchy diagram are coded except one:
the PasswordInternalException class. The PasswordInternalException class noti-
fies programs when the Password class generates an exception due to an internal
problem with storing the password list.
The PasswordInternalException class also inherits from the abstract base
class, PasswordException. As shown in Figure 10-3 on page 609, however, it is
designated as a leaf node, which means it cannot have any child classes;
therefore, it is not extensible.
Generally, class designers expect their classes to be extended. Often, they build
classes, as in this chapter, specifically for the purpose of extending them. On occa-
sion, the designer will build a class that should not be extended. To do so might
open an opportunity for some misuse of the system, expose some vulnerability, or
simply not be necessary. In this chapter, the PasswordInternalException class is
not to be extensible; that is, it should be defined as a final class. A final class in
Java is a class that cannot be extended; that is, it is a class that can be only a child
class and not a parent class. In Java, the means for inhibiting extensibility of a
class is to declare the class with the final qualifier.
Because final classes cannot be extended, think of them as dead ends in your
inheritance hierarchy. Use care when making a class final, as it is difficult to
foresee future uses of your class.
FIGURE 10-19
Final Classes
By making a class final, you are not allowing any new classes
to enhance its functionality. Before making a class final, be certain
this truly is necessary, as it is difficult to foresee future uses of your
class.
 
Search WWH ::




Custom Search