In this program, we declare two classes: Point and Circle. The Point class declares two private variables: x and y. The Circle class declares a final variable called CENTER _POINT of type Point, as follows:
private final Point CENTER_POINT = new Point(0, 0);
The final variable CENTER_POINT is initialized to a Point object having its x and y coordinates set to (0,0). Note that CENTER_POINT holds a reference to a Point object having the value (0, 0).
This represents the centre of the circle. Now, the question is, can we change these coordinates to change the circle’s centre before drawing a new circle? In the drawCircle method, we call the setX and setY methods of the Point class to change the values of the x and y fields, as shown here:
public void drawCircle()
If we compile this code, it will compile without any errors because the CENTER_POINT variable, which is of the constant type, points to a Point object that has its state initially set to (0,0). The contents of the Point object—that is, (0,0) —are themselves not constant and therefore can be modified.
If a final variable holds a reference to an object, the reference must remain constant, not the object. We can change the object’s state by invoking mutator methods on it.
Now, consider the case where you try to assign another Point object to the CENTER_POINT variable, as follows:
CENTER_POINT = new Point(50, 50); // illegal assignment
Compiling this statement results in a compilation error because the CENTER_POINT object should always point to the fixed object reference to which it is initialized. It cannot refer to any other instance of the Point class. A final variable of the class type cannot refer to any object other than the object reference to which it has been set.
Important Points Related to the final Keyword
Here is a summary of the important points you should keep in mind when using the final keyword:
- We cannot subclass (extend) a final class.
- We cannot override a final method.
- A final variable that is a field of a class is a constant.
- A blank final variable (field) is a variable that is declared “final” but not initialized.
- A blank final variable (field) must be initialized in a constructor. If the variable is initialized in a constructor, you must initialize it in all the overloaded constructors of the class.
- A blank final variable (field) can be set only once.
- A blank final variable (field) must be set before it is used anywhere.