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:
finalis 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 theObjectclass, 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:
finalis a keyword for controlling code modification.finalizeis a method for cleanup before garbage collection, deprecated and not recommended for use.