Monday, 7 October 2013

Final Classes

               You can declare that your class is final; that is, that your class cannot be sub-classed  There are (at least) two reasons why you might want to do this: security reasons and design reasons.
               1.Security: One mechanism that hackers use to subvert systems is to create sub-classes of a class and then substitute their class 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 prevent any sub-classes from being created. The String class in the java.lang package is a final class for just this reason. The String class is so vital to the operation of the compiler and the interpreter that the Java system must guarantee that whenever a method or object uses a String they get exactly a java.lang.String and not some other 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 will print an error message and refuse to compile your program. In addition, the byte code versifier ensures that the subversion is not taking place at the byte code level by checking to make sure that a class is not a subclass of a final class.
              2.Design: Another reason you may wish to declare a class as final are for object-oriented design reasons. You may think that your class is "perfect" or that, conceptually, your class should have no sub-classes.
To specify that your class is a final class, use the keyword final before the class keyword in your class declaration. For example, if you wanted to declare your (perfect) Chess-algorithm class as final, its declaration would look like this:
final class ChessAlgorithm {
    . . .
}
Any subsequent attempts to subclass ChessAlgorithm will result in a compiler error such as the following:
Chess.java:6: Can't subclass final classes: class ChessAlgorithm
class BetterChessAlgorithm extends ChessAlgorithm {
      ^

1 error

No comments:

Post a Comment