Java Reference
In-Depth Information
Because meth( ) is declared as final , it cannot be overridden in B . If you attempt to do so,
a compile-time error will result.
final Prevents Inheritance
You can prevent a class from being inherited by preceding its declaration with final . De-
claring a class as final implicitly declares all of its methods as final , too. As you might
expect, it is illegal to declare a class as both abstract and final since an abstract class is
incomplete by itself and relies upon its subclasses to provide complete implementations.
Here is an example of a final class:
As the comments imply, it is illegal for B to inherit A since A is declared as final .
Using final with Data Members
In addition to the uses of final just shown, final can also be applied to member variables to
create what amounts to named constants. If you precede a class variable's name with final ,
its value cannot be changed throughout the lifetime of your program. You can, of course,
give that variable an initial value. For example, in Chapter 6 a simple error-management
class called ErrorMsg was shown. That class mapped a human-readable string to an error
code. Here, that original class is improved by the addition of final constants which stand
for the errors. Now, instead of passing getErrorMsg( ) a number such as 2, you can pass
the named integer constant DISKERR .
Search WWH ::




Custom Search