You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
16. ### What is finalize method? How do you override it?
508
+
The `finalize()` is a method from the Object classused to perform cleanup activity before destroying any object. The method is invoked by garbage collector for cleanup activities like closing the resources associated with an object(database connection or network connection). This process is known as **finalization** and it helps JVM for in-memory optimization.
509
+
510
+
It is a protected method of Object classwith syntax as shown below,
511
+
```java
512
+
protected void finalize() throws Throwable{}
513
+
```
514
+
515
+
Since Object is the superclassof all java classes, the finalize method is available for every java class. That's why garbage collector can call the `finalize()` method on any java object.
516
+
517
+
This method has empty implementation inside Object class. If your classhas clean-up activities, you need to override this method. The following example demonstrate how to override the finalize method and call the method explicitly.
518
+
519
+
```java
520
+
import java.lang.*;
521
+
522
+
publicclassfinalizeDemo {
523
+
524
+
protectedvoidfinalize() throwsThrowable {
525
+
try {
526
+
527
+
System.out.println("Inside finalize() method of finalizeDemo class");
528
+
}
529
+
catch (Throwable e) {
530
+
531
+
throw e;
532
+
}
533
+
finally {
534
+
535
+
System.out.println("Calling finalize method of the Object(super) class");
0 commit comments