June 30, 2015

final variable, final method and final class

Final Variable:

A final variable is a variable which has been initialized to a fixed value and it cannot be changed after initialization.

When to use Final variable ?

Use final when you do not want the variable to be modified , Example : daysOfWeek,hourseOfDay etc.
Lets see how to define a final variable in Java with the below example :

Output would be
Days in a week = 35

Common error while using the final variable:

Here is the common error while using the final variable

you will ge tthe following error on compilation.

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The final local variable daysInWeek cannot be assigned. It must be blank and not using a compound assignment

Final Method :

A final method is a method which cannot be overridden by a subclass. Lets create a superclass to understand the final method concept.

And we can create a subclass by extrending the super class as below.

now let’s create a class to access the subclass methods as below


Exception in thread “main” java.lang.VerifyError: class SubClass overrides final method .ÓÙ*h’+
at java.lang.ClassLoader.defineClass1(Native Method)

at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at Sample.TestOverriding.main(TestOverriding.java:5)

Final class :

A final class is a Java class which cannot be extended. This means that a final class can not become a superclass nor have a subclass.

An example final class is written below:

final class A {}

then that means that A cannot be further extended or subclassed.
This feature has a couple of big implications. One is that it allows control over a class, so that no one can subclass the class and possibly introduce

anomalous behavior. For example, java.lang.String is a final class. This means, for example, that I can’t subclass String and provide my own length() method

that does something very different from returning the string length.
There is also a big performance issue with final classes. If a class is final, then all of its methods are implicitly final as well, that is, the method is

guaranteed not be overridden in any subclass. A Java compiler may be able to inline a final method.

Leave a Reply