Final Classes Cannot Be Superclasses
A final class cannot extended to create a subclass. All methods in a final
class are implicitly final
. Class String
is an example of a final
class. If you were allowed to create a subclass of String
, objects of that subclass could be used wherever String
s are expected. Since class String
cannot be extended, programs that use String
s 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.
We’ve now discussed declaring variables, methods and classes final
, and we’ve emphasized that if something can be final
it should be final
. Compilers can perform various optimizations when ...
Get Java™ How To Program (Early Objects), Tenth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.