Three key words in Java: final finally finalize

  • 2020-07-21 08:11:12
  • OfStack

final

When this keyword modifies a class, it means that it cannot be subclassed, that is, it cannot be inherited, so a class cannot be declared as abstract and final at the same time. When final modifies variables or methods, it ensures that they are not changed during use. Variables declared as final must be given an initial value at initialization time and can only be referenced and not modified for later use. Also, when final modifies a method, the method cannot be overloaded.

finally

finally is provided for exception handling to perform any clear operations. If an exception is thrown, the matching catch clause is executed, and control is transferred to the finally block.

finalize

The method name. The finalize method calls the finalize() method for early cleanup when the garbage collector performs memory object cleanup. This method is called by the garbage collector when it determines that the object is not referenced. It is defined in the Object class, so all classes inherit from it. Subclasses override the finalize() method to clean up system resources or perform other cleanup. The finalize() method is called on an object before the garbage collector removes it.

All the classes in Java inherit the finalize() method from the Object class. When the garbage collector (garbage colector) decides to reclaim an object, the object's finalize() method is run. It's worth noting to C++ programmers that the finalize() method is not synonymous with destructors. There is no destructor in Java. The destructor of C++ runs when an object dies. Since C++ has no garbage collection, the object space is collected manually, so once an object is not used, the programmer should drop it delete(). So destructors often do some last-minute work like file saving. Unfortunately in Java, if memory is always sufficient, garbage collection may never take place, which means that filalize() may never be executed, and it is obviously not reliable to expect it to do the finishing work.

So what exactly does finalize() do? Its primary use is to reclaim memory from special channels. The Java program has a garbage collector, so memory problems are generally not a programmer's concern. But there is one type of JNI(Java Native Interface) that calls the ES53en-ES54en program (C or C++), and the job of finalize() is to reclaim this part of memory.


Related articles: