Sobes.tech
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:

  • final is 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 the Object class and can be overridden to release resources before the object is garbage collected. However, its use is not recommended because calling finalize() 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.

Can you explain the difference between the keyword… - sobes.tech