Saturday, 5 October 2013

final keyword in Java


           Final keyword in java has different usage based on the context in which it is used.
Final keyword can be used for variables, class or methods with giving different meaning to them respectively. 
It is used for below types in java.
a.   Class
b.   Methods
c.   Variables

Class:
A class declared with final keyword cannot be derived. Implicitly all the methods defined in a final class are final. Many classes in java library are declared as final. One of the very known example is java.lang.String class.
Note:
a.   An Abstract class cannot be declared final.
b. Using private and final both at the same time for a class makes the final redundant as the private class itself cannot be accessed by its sub classes.

Syntax:
Public final class Sample
{
}

Example:
Public final class FinalClass{}  -- declaring a class as final
Public class DerrivedClass extends FinalClass{} – this is not allowed.

Methods:
                A final method cannot be overridden or hidden by sub classes. This functionality is used where we need to take care that a subclass should not alter the behavior of a method to maintain consistency of the class.
Note:
An Abstract method cannot be declared final.

Syntax:
Public final void method()
{
                System.out.println(“in final method”);
}

Example:
Public class Sample
{
                Public final void method();
}

Public class DerrivedSample extends Sample
{
                Public voif method() --- This is not possible.
}

Variables:
                A variable declared final can bee initialized only once. It may be initialized value at the time of declaration or by assignment. A final variable which is not initialized at time of declaration is called “blank final” variable.

Note:
a. The blank final variable needs to be initialized in constructor else it results in compile time error and similarly, final blank static variable needs to be initialized in static initialization.
b. When a reference is made final, that means that this reference cannot be made point to any other object but the object to which it is pointing can be modified if that is a mutable class object.

Syntax:

public final int PI = 3.14;

No comments:

Post a Comment