Junior
What is the keyword 'final' and the method 'finalize' in Java, and what is the difference between them?
sobes.tech AI
Answer from AI
The keyword final is used to restrict modification.
- For variables: the value of the variable cannot be changed after initialization.
- For methods: the method cannot be overridden in a subclass.
- For classes: the class cannot be inherited.
The finalize() method is a method of the Object class, which is called by the garbage collector just before the object is removed from memory, giving the last chance to perform resource cleanup operations. There are no guarantees that this method will be called.
// Example of using final
final int CONSTANT_VALUE = 100;
// CONSTANT_VALUE = 200; // Compilation error
class BaseClass {
final void finalMethod() {
// Method body
}
}
class DerivedClass extends BaseClass {
// @Override
// void finalMethod() { // Compilation error, method is final
// // Method body
// }
}
final class FinalClass {
// Class body
}
// class AnotherClass extends FinalClass { // Compilation error, cannot inherit from a final class
// // Class body
// }
// Example of using finalize
class Resource heavyResource; // Some resource
class MyObject {
public MyObject() {
heavyResource = new Resource(); // Resource initialization
}
@Override
protected void finalize() throws Throwable {
try {
// Cleanup resource before object removal
if (heavyResource != null) {
heavyResource.release();
}
} finally {
super.finalize(); // Important to call superclass finalize
}
}
}
Differences:
| Characteristic | final | finalize() |
|---|---|---|
| Purpose | Restricts modification (immutability, prohibits overriding/inheritance) | Cleans up resources before object removal by the garbage collector |
| Applies to | Variables, methods, classes | Method of the Object class |
| Called | Not called, it's a modifier | Called by the garbage collector (no guarantee) |
| Keyword | Yes | No, it's a regular method |