Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

10.6 final Methods and Classes

We saw in Sections 6.3 and 6.9 that variables can be declared final to indicate that they cannot be modified after they're initialized—such variables represent constant values. It's also possible to declare methods, method parameters and classes with the final modifier.

Final Methods Cannot Be Overridden

A final method in a superclass cannot be overridden in a subclass—this guarantees that the final method implementation will be used by all direct and indirect subclasses in the hierarchy. Methods that are declared private are implicitly final, because it's not possible 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.

Final Classes Cannot Be Superclasses

A final class that's 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. If you were allowed to create a subclass of String, objects of that subclass could be used wherever Strings are expected. Since class String cannot be extended, 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 insights on the use of keyword final, visit

download.oracle.com/javase/tutorial/java/IandI/final.html

and

www.ibm.com/developerworks/java/library/j-jtp1029.html
  • + Share This
  • 🔖 Save To Your Account