final Methods and Classes
We saw in Section 6.10 that variables can be declared final to indicate that they cannot be modified after they are declared and that they must be initialized when they are declaredsuch variables represent constant values. It is also possible to declare methods and classes with the final modifier.
A method that is declared final in a superclass cannot be overridden in a subclass. Methods that are declared private are implicitly final, because it is impossible to override them in a subclass (though the subclass can declare a new method with the same signature as the private method in the superclass). Methods that are declared static are also implicitly final, because static methods cannot be overridden either. A final method's declaration can never change, so all subclasses use the same method implementation and calls to final methods are resolved at compile timethis is known as static binding. Since the compiler knows that final methods cannot be overridden, it can optimize programs by removing calls to final methods and replacing them with the expanded code of their declarations at each method call locationa technique known as inlining the code.
Performance Tip 10.1
The compiler can decide to inline a final method call and will do so for small, simple final methods. Inlining does not violate encapsulation or information hiding, but does improve performance because it eliminates the overhead of making a method call. |
A class that is declared final cannot be a superclass (i.e., a class cannot extend a final class). All methods in a final class are implicitly final. Class String is an example of a final class. This class cannot be extended, so programs that use Strings can rely on the functionality of String objects as specified in the Java API. Making the class final also prevents programmers from creating subclasses that might bypass security restrictions. For more information on final classes and methods, visit java.sun.com/docs/books/tutorial/java/javaOO/final.html. This site contains additional insights into using final classes to improve the security of a system.
Common Programming Error 10.5
Attempting to declare a subclass of a final class is a compilation error. |
Software Engineering Observation 10.6
In the Java API, the vast majority of classes are not declared final. This enables inheritance and polymorphismthe fundamental capabilities of object-oriented programming. However, in some cases, it is important to declare classes finaltypically for security reasons. |