The difference between final, finally, and finalize in Java
Final
- When applied to a primitive variable, the value of the variable cannot be changed.
- When applied to a reference variable, the reference variable cannot point to any other object on the heap.
class Foo {
public static void main(String[] args)
{
// Non final variable
int a = 5;
// Final variable
final int b = 6;
// Allowed to modify to the non final variable
a++;
// Compile time error
// We cannot modify the final variable
b++;
}
}
When applied to a method, the method cannot be overridden.
class Foo {
final void calculate() {
// ...
}
}
class Bar extends Foo {
// Compile time error
// We cannot extend calculate(), because it is final
void calculate() {
// ...
}
}
When applied to a class, the class cannot be subclassed.
final class Foo {
// ...
}
// Compile time error
// We cannot extend Foo, because it is final
class Bar extends Foo {
// ...
}
Finally
After the try
block or after the catch
block, there is an optional finally
block. If the JVM does not exit from the try
block, the statements in the finally
block will always be executed.
Usually, the finally
block is used to write the clean up code.
Finalize
This is the method that the JVM runs before running the garbage collector.