Tuesday, December 13, 2011

What is the use of final keyword?

final keyword: If a variable is declared as final, it's value can not be changed. If we try to change the value of a variable which is declared as final, it gives error.


Example:
final int MAX=0;
MAX++; //error.


Another use of final keyword: If a method is declared as final it can not be overridden. So to prevent method overriding we can use final keyword.

Example:
class A
{
void show()
{
System.out.println("Base Class");
}
}
class B extends A
{
void show() //Error, it can not be overridden
{
System.out.println("Sub Class") ;
}
}

Another use of final: If a class is declared as final, it can not be inherited. So to prevent inheritance we can use final keyword.

Example:
final class A
{
}
class B extends A //Error,it can not be inherited
{
}