Saturday, 28 November 2015

Java final Keyword

final keyword in Java


There are three uses of final keyword in Java :

  1. To declare named constants
  2. To prevent a class from being inherited
  3. To prevent a method from overriding 
We will discuss here all these one by one.

Declaring constants:

A variable can be declared as final. Doing so prevents its contents from being modified. This means that you must initialize a final variable when it is declared.
(In this usage, final is similar to const in C/C++/C#.) For example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
Variables declared as final does not occupy memory on per-instance basis.

Preventing inheritance:

Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration with final. Declaring a class as final implicitly declares all of its methods as final, too. As you might expect, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations.
Here is an example of a final class:
final class A
{
// ...
}
// The following class is illegal.
class B extends A
// ERROR! Can't subclass A
// ...
}
As the comments imply, it is illegal for B to inherit A since A is declared as final.

Preventing Overriding: 

While method overriding is one of Java’s most powerful features, there will be times when you will want to prevent it from occurring. To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden. The following fragment illustrates final:
class A 
{
          final void meth()
         {
                   System.out.println("This is a final method.");
          }
}
class B extends A
{
          void meth()
          {
               // ERROR! Can't override
          }
}

Note:
Also if a method in Java if declared as final it is telling the compiler to make its definition inline as its definition will not be changed by the subclasses. 

No comments:

Post a Comment