Sobes.tech
Junior

Mis on Java keeles võtmesõnad final ja finalize ning millised on nende erinevused?

sobes.tech AI

Vastus AI-lt

In Java, final and finalize are different concepts with different purposes:

  • final is a keyword used to declare:
    • Constants (variables that cannot be changed after initialization).
    • Methods that cannot be overridden in subclasses.
    • Classes that cannot be inherited.

Example:

final int x = 10; // x cannot be changed
final class MyClass {} // class cannot be inherited
final void myMethod() {} // method cannot be overridden
  • finalize() is a method of the Object class, called by the garbage collector before removing the object from memory. It is intended for resource cleanup, but its use is not recommended, as its invocation is not guaranteed and can lead to unpredictable behavior.

Example:

@Override
protected void finalize() throws Throwable {
    // resource cleanup
    super.finalize();
}

Differences:

  • final is a keyword for controlling code modification.
  • finalize is a method for cleanup before garbage collection, deprecated and not recommended for use.