finalize(), finally and final in Java

There’s some confusion in the mind of an intermediate level programmer about finalize(),finally and final in java. So to remove that confusion from each and everyone’s mind I thought of writing a post on it.

finalize() : A Method
finally : A Clause in Try-Catch
final : Keyword in java

finalize :

It is called by the garbage collecter on an object by garbage collection when it knows that there is no references on the object. The finalize() method is defined in the java.lang.Object class and its modifier is defined as protected. The finalize() method is not public because it should only be invoked by JVM and not by anyone else and protected so that it can be overridden by the subclasses.

You can override the finalize() method and the declaration of the method should look like this :

protected void finalize() throws throwable

Ex.

The below class opens the file when constructed :

class OpenAFile {
FileInputStream aFile = null;
OpenAFile(String filename) {
try {
aFile = new FileInputStream(filename);
} catch (java.io.FileNotFoundException e) {
System.err.println(“Could not open file ” + filename);
}
}
}

As a part of good programming practice, the open file should be closed :

protected void finalize () throws throwable {
if (aFile != null) {
aFile.close();
aFile = null;
}
}

It is important to understand that finalize() is only called just prior to garbage collection. It is not called when an object goes out-of-scope, for example. This means program should provide other means of releasing system resources, etc., used by the object. It must not rely on finalize() for normal program operation.

finally :

The finally clause defines a code that always executes, regardless of whether the exception was caught. The following sample code is taken from the book by Frank Yellin:

try {
startFaucet();
waterLawn();
} catch (Exception e) {
logProblem(e);
} finally {
stopFaucet();
}

In the above example the Faucet is turned off regardless of whether the exception was caught or not. The code inside the braces after try is called the protected code.

The only thing that stop finally from executing are virtual machine shutdowns i.e. System.exit method etc.

The final keyword in Java

Like other keywords in java, final is also a keyword used in several different contexts to define an entity which cannot later be changed.

Here in this tutorial we will be dealing with final classes, final methods, final variables and also I will be covering blank final variables.

    final classes

The Java Programming language permits us to apply the keyword final to classes. If the class is made final then it cannot be sub-classed.

Ex :

The java.lang.String is a final class. This is done for security reasons, because it ensures that if the method is referenced as String then the method is a definite string of class String and not a string of class which has sub-classed String class.

    final methods

Like class we can also mark methods as final. Methods that are marked as final cannot be overridden in any case. For security reasons only you must make the method as final if the method has implementation which you don’t want others to change.

Methods declared as final can be optimized. The compiler can generate a code that causes a direct call to the method, rather than invoking it the usual way i.e during the run-time.

    final variables

If a variable is marked as final then the value of that variable cannot be changed i.e final keyword when used with a variable makes it a constant. And if you try to change the value of that variable during the course of your program the compiler will give you an error.

NOTE: If you mark variable of a reference type as final, that variable cannot refer to any other object. However, you can change the object’s contents, because only the reference itself is final.

    Blank final variables

A blank final variable is a variable that is not initialized during its declaration. The initialization is delayed. A blank final instance variable must be assigned in a constructor, but it can be set only once. A blank final variable that is local variable can be set at any time in the body of the method, but it can be set only once.

The following code fragment is an example of how a blank final variable can be used in class.

public class Customer{
private final long customerID;

public Customer(){
customerID = createID();
}

public long getID(){
return customerID;
}

public long createID(){
return … // generates new ID
}
… // more declarations
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: