Junior — Middle
Can you explain the difference between the keyword final and the finalize method in Java?
sobes.tech AI
Answer from AI
In Java, the keyword final and the method finalize() serve completely different purposes:
-
finalis a modifier that can be applied to classes, methods, and variables.- For a class: it cannot be subclassed.
- For a method: it cannot be overridden in subclasses.
- For a variable: its value cannot be changed after initialization.
-
finalize()is a method defined in theObjectclass and can be overridden to release resources before the object is garbage collected. However, its use is not recommended because callingfinalize()is not guaranteed and can lead to unpredictable behavior.
Example of using final:
final class Constants {
public static final double PI = 3.14159;
}
class MyClass {
public final void doSomething() {
// this method cannot be overridden
}
}
The finalize() method looks like this:
@Override
protected void finalize() throws Throwable {
try {
// resource cleanup
} finally {
super.finalize();
}
}
But it is better to use other resource management mechanisms, such as try-with-resources.