The final keyword can be applied to declaration of classes, methods and variables.
- Final class: if a class is marked as final, it cannot be subclassed/inherited by another class. For example:
then the following code will not compile:1
final
class
A { }
1
class
B
extends
A {}
// compile error
- Final method: when a method is final, that means it cannot be overriden, neither by methods in the same class or in sub class. For example:
the subclass D attempts to override the method foo(), but fail because foo() is marked as final:1
2
3
class
C {
final
void
foo() { }
}
1
2
3
class
D
extends
C {
void
foo() { }
// compile error
}
- Final variable: if a variable is marked as final, its reference cannot be changed to refer to another object, once initialized. For example:
Once the variable message is initialized and marked as final, the following code attempts to assign another value to it, will fails:1
final
String message =
"HELLO"
;
1
message =
"BONJOUR"
;
// compile error
Note: a class cannot be both abstract and final.(because the purpose of an abstract class is to be inherited.)
How Java final modifier affect your code
1. Final Class
When a class is marked as final, it cannot be subclassed. In other words, if we don’t want a class to be able to be extended by another class, mark it as final. Here’s an example:
1 2 |
|
If we try to extend this final class like this:
1 2 |
|
Compile error: error: cannot inherit from final PrettyCat
So the final modifier is used to prevent a class from being inherited by others. Java has many final classes: String, System, Math, Integer, Boolean, Long, etc.
NOTES:
- There is no final interface in Java, as the purpose of interface is to be implemented.
- We cannot have a class as both abstract and final, because the purpose of an abstract class is to be inherited.
2. Final Method
When a method is marked as final, it cannot be overridden. Let’s look at the following example:
1 2 3 4 5 |
|
Here, the meow() method is marked as final. If we attempt to override it in a subclass like this:
1 2 3 4 5 |
|
The Java compiler will issue a compile error: error:
1 |
|
So use the final keyword to modify a method in case we don’t want it to be overridden.
3. Final Variable
When a variable is marked as final, it becomes a constant - meaning that the value it contains cannot be changed after declaration. Let’s see an example:
1 |
|
If we try to assign another value for this final variable later in the program like this:
1 |
|
The compiler will complain:
1 |
|
For reference variable:
1 |
|
After this declaration, myCat cannot point to another object.
In Java, constants are always declared with the static and final modifiers, for example:
1 |
|
The final modifier can be also used in method’s arguments. For example:
1 2 |
|
This means code in the method cannot change the theCat variable.