- 10.1 Introduction
- 10.2 Polymorphism Examples
- 10.3 Demonstrating Polymorphic Behavior
- 10.4 Abstract Classes and Methods
- 10.5 Case Study: Payroll System Using Polymorphism
- 10.6 final Methods and Classes
- 10.7 Case Study: Creating and Using Interfaces
- 10.8 (Optional) Software Engineering Case Study: Incorporating Inheritance into the ATM System
- 10.9 Wrap-Up
10.6 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 initialized—such variables represent constant values. It is also possible to declare methods, method parameters 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. Methods that are declared static are also implicitly final. 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 time—this 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 location—a technique known as inlining the code.
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/IandI/final.html. This site contains additional insights into using final classes to improve the security of a system.