Page 361 - Computer_Science_F5
P. 361
Computer Science piece of code example of overloading constructor:
public class Book {
String title;
String author;
// This code shows constructor with two parameters
FOR ONLINE READING ONLY
public Book(String t, String a) {
title = t;
author = a;
}
// This code shows overloaded constructor with three parameters
public Book(String t, String a, int pages) {
title = t;
author = a;
pageCount = pages;
}
}
(f) Destructors in Java (i) Syntax of a finalize() method
Destructors in Java are effectively The following is a syntax for the finalize()
simulated through the finalize() method. method:
This method serves a purpose similar
to that of traditional destructors. Java protected void finalize() {
works for a destructor with the help //finalization code is put here
of the Garbage collection. When a }
program need to call the destructor
in Java, the finalise method must be To incorporate a finalizer into a class,
used. This method is not independent you simply define the finalize() method.
because it relies on Garbage Collection. Whenever the Java runtime system
The garbage collector is a thread that is ready to reclaim an object of that
deletes or destroys the object which has class, it invokes this method. Within
no use in the heap area. For example, if the finalize() method, you specify
an object is linked to file, database, or the necessary actions that should be
network connections, it must first close executed before the object is deleted.
all associated connections before being
deleted. This ensures that resources In this context, the modifier “protected”
are properly released prior to garbage restricts access to the finalize() method.
collection. The functions are closed by It is important to note that finalize() is
calling the finalize() method. invoked right before garbage collection
352
for Advanced Secondary Schools
Computer Science Form 5.indd 352 23/07/2024 12:34

