|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
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
- Security: One mechanism that hackers use to subvert systems is to create a subclass of a class and to then substitute the subclass for the original. The subclass looks and feels like the original class but does vastly different things, possibly causing damage or getting into private information. To prevent this kind of subversion, you can declare your class to be final and thereby prevent any subclasses from being created. The
Stringclass is a final class for just this reason. This class is so vital to the operation of the Java platform that it must guarantee that whenever a method or an object uses aString, it gets exactly ajava.lang.Stringand not another kind of string. This ensures that all strings have no strange, inconsistent, undesirable, or unpredictable properties.If you try to compile a subclass of a final class, the compiler prints an error message and refuses to compile your program. In addition, the Java runtime system ensures that the subversion is not taking place at the bytecode level. It does this by checking to make sure that a class is not a subclass of a final class.
- Design: You may also wish to declare a class as final for object-oriented design reasons. You may think that your class is "perfect" or that, conceptually, your class should have no subclasses.
finalbefore theclasskeyword in your class declaration. For example, if you wanted to declare your (perfect)ChessAlgorithmclass as final, its declaration should look like this:Any subsequent attempts to subclassfinal class ChessAlgorithm { ... }ChessAlgorithmwill result in a compiler error.
If declaring an entire classfinalis too heavy-handed for your needs, you can declare some or all of the class's methods final instead. Use thefinalkeyword in a method declaration to indicate that the method cannot be overridden by subclasses. TheObjectclass 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
ChessAlgorithmclass final, you might want thenextMovemethod to be final instead:class ChessAlgorithm { ... final void nextMove(ChessPiece pieceMoved, BoardLocation newLocation) { ... } ... }
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.