Finalizer Methods

Finalizer methods are almost the opposite of constructor methods. A constructor method is used to initialize an object, and finalizer methods are called just before the object is collected for garbage and has its memory reclaimed.

The finalizer method is finalize(). The Object class defines a default finalizer method that does nothing. To create a finalizer method for your own classes, override the finalize() method using this signature:

protected void finalize() throws Throwable { 
    super.finalize();
}

Note

The throws Throwable part of this method definition refers to the errors that might occur when this method is called. Errors in Java are called exceptions; you learn more about them on Day 16, "Error Handling and Security." ...

Get Sams Teach Yourself Java 2 in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.