Prev | Next |
The final keyword
The keyword final restricts the modifiability of attributes, methods or class when applied to them. It is primarily used to prevent any intentional or non-intentional modification.
1. Final attributes
An attribute is declared 'final' if it should remain a constant during the entire execution. For example, the value of pi is fixed and should not be allowed to change. See example below:
public class Circle { protected int radius; protected Point center; protected final float pi = 3.14; // Cannot be modified public double area() { // Your code here } public double circumference() { // Your code here } }
Note: Since pi value remains constant throughout, it is better to declare it as:
- static so that it can be accessed by the class name without the need to instantiate.
- public so that it can be accessed direclty without having to invoke any methods.
public static final float pi = 3.14; // can be accessed by Circle.pi
Exercise: Try reassigning the pi value in your source code and check what happens.
2. Final methods
A final method cannot be overriden. In a sense, its method of operation remains the same and cannot be changed in future. It is useful when you don't want the feature to be twisted. For example,
public final double area() { return pi * r * r; }
will prevent the user of this class from twisting its behavior by giving an incorrect formula. If it is not final, it is possible for an user to twist its behavior as follows.
public class CircleX extends Circle { public void area() { // overriding Circle's area() return pi * r; // An incorrect formula } }
Any method implementing an universally accepted behavior must be declared final.
Exercise: Try overriding a final method and check what happens.
3. Final class
The keyword final, when applied to a class, prevents the class from being extended. Typically, a class is declared final if all the methods in the class should not be overriden. Rather than declaring every method as final, it is convenient to declare the class a final.
The String class of the Java library is a final class. It is referred to as immutable since
- It is declared final and hence none of its methods can be twisted.
- None of its methods alter its own state. i.e. each operation will return a new String object with the required effect, but will never alter its state.
Exercise: Try extending a final class and check what happens.