- HubPages»
- Technology»
- Computers & Software»
- Computer Science & Programming
Java: The Final Keyword
Introduction
For better or worse, designers of the Java programming language elected to use the keyword final in multiple contexts. In this tutorial we will examine three popular applications of the keyword: final classes, final methods, and final properties. We present code snippets illustrating the application of each construct and we discuss software engineering scenarios in which these keywords may be useful.
A final class cannot be used as a base class. A final method in a base class cannot be overridden in a derived class. A final property cannotprogrammatically be assigned a new value. Obviously each use of the keyword has a slightly different meaning and is used in a different context. With some study and practice, programmers and analysts should have no problem applying and deciphering code that uses these keywords.
Final Classes in Java
Generally speaking, any Java class can be used as a base class, unless it is declared with the keyword final. Consider the difference between these two class declarations:
public class myClass{ // ... } final public class myFinalClass{ //... }
Given the above code snippets, here are examples of what to do and what not to do:
// This will compile public class myDerivedClass extends myClass { //... } // This will not compile! public class myDerivedClass extends myFinalClass { //... }
In line 7 of the the preceding code snippet, an attempt is made to inherit from the class called myFinalClass, which was declared in line 5 of the earlier snippet to be a final class. By definition, a final class cannot be used as a base class. The code will generate a build error along the lines of "The type myDerivedClass cannot subclass the final class FinalClass".
This error can be remedied in two different ways:
- Remove the reference to FinalClass in the declaration of myDerivedClass, or
- Remove the final keyword from the declaration of FInalClass.
Final Methods in Java
Next, we move on to a discussion of final methods in Java. Like final classes, the keyword final can be applied to a method, but the meaning is slightly different.
A method declared as final cannot be overridden in a derived class. Consider the following code snippet for an illustration of this keyword.
/** * Demonstrate a final class method * @author nicomp */ public class FinalClassMethod { /** * This method can be inherited but * not overridden in the derived class. * (no polymorphism) */ final public void HelloWorld() { System.out.println("Hello World"); } /** * This class method can be overridden because * it's not declared as final. * @param msg The message that will be written to stdout */ public void HelloWorld(String msg) { System.out.println("Hello World: " + msg); } }
In line 11 of the preceding code snippet, the method HelloWorld() is declared as final. This keyword prevents any class that inherits from the FinalClassMethod class from overriding the definition of HelloWorld(). Attempting to do so will result in a compilation error.
Refer to the following code snippet for examples of what to do and what not to do:
// This class attempts to override a method // in its' base class that has been declared // as final. A compilation error will result. public class Oops extends FinalClassMethod { public void HelloWorld() { System.out.println("Hello from the Oops class"); } }
Line 6 of the previous code snippet will be the site of a compilation error long the lines of "Cannot override the final method from FinalClassMethod." This error can be removed by removing the final keyword from the declaration of the HelloWorld() method in the base class.
Note that the HelloWorld(String s) method in the base class can be overridden.
Final Class Properties
Applying the final keyword to a class property causes that property to be treated as a program constant. This is analogous to the const keyword in C++.
In the following code snippet we illustrate how to declare a class property as final and how to initialize it in the constructor:
/** * Illustrates a class member that cannot be changed * @author nicomp * */ public class FinalClassMember { // This class member cannot be assigned a new value // It's final, but it needs to be initialized somehow final private int width; /** * The default constructor. */ public FinalClassMember() { // We can assign the 'final' member a value here. // This provides the initialization width = 42; } /** * @return The width of the object */ public int GetWidth() {return width;} /** * * @param width The new value of the width of the object * @return The new value */ public int SetWidth(int width) { // Compilation error: // The final field FinalClassMember.width // cannot be assigned this.width = width; // oops! return width; } }
Line 35 of the previous code snippet will generate a compilation error along the lines of "The final field FinalClassMember.width cannot be assigned." This error can be remedied in one of two ways:
- Remove line 35 from the method
- Remove the final keyword from the declaration of the property, width.
Practical applications of the Final Keyword in Java
We have introduced and discussed three different applications of the final keyword in Java. it is interesting to consider why these keywords might be useful to the programmer. All programmers are expected to have a thorough understand of the nuances of their language(s) of choice in order to write the most robust and maintainable programs. Using the final keyword correctly can certainly make Java code 'safer' in that programming errors may be reduced.
As discussed above, a class declared as final cannot be used as a base class. This strategy will prevent programmers from accidentally inheriting the class and adding functionality that may not be appropriate. In most circumstances, a class is meant to be used as a base class, but in the narrow situations where a class is logically 'complete', it's a good programming practice to prevent other developers from using it as a base class.
As discussed above, a method declared as final cannot be overridden in a derived class. The method is still inherited by the derived class, but a method with the same signature cannot be included in the derived class. This will reduce the possibility of the derived class replacing crucial logic in the base class. Of course, the derived class can still completely ignore the final method in the base class, but logic errors cannot be detected by the Java compiler.
As discussed above, a class property declared as final cannot be assigned a new value. This is the Java technique for creating program constants. Constants are a staple of any programming language. Any class property that should not change should be declared as a final: it's a simple and effective programming convention that is easy to follow. For example:
private final int PI = 3.1415927;
The value of PI should remain constant throughout the class. By declaring PI as final, potential programming errors are eliminated. Any attempt to assign a new value to PI will result in a compilation error that is obvious and simple to remedy.
Conclusion
The Java programming language uses the keyword final in multiple contexts. We have introduced and discussed three different applications of the keyword: final classes, final class methods, and final class properties.