1 Aug 2012

Final Variable in Java


Any variable either member variable or local variable (declared inside method or block) modified by final keyword is called final variable. Final variables are often declare with static keyword in java and treated as constant.

In Java to make any thing thing as constant we use a keyword final.
The final keyword is placing an important role in three levels.They are

1. At variable level

syntax:    final datatype variable_name=variable_value;
example: final int a=10;

Therefore final variable values can not be modified.

2. At method level

Final keyword in java can also be applied to methods. A java method with final keyword is called final method and it can not be overridden in sub-class. You should make a method final in java if you think it’s complete and its behavior should remain constant in sub-classes. Final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded on compile time.

syntax: final return type method_name(list_of_parameters)
{
//body
}

Once the method is final which can not be overridden.

3. At class level

Java class with final modifier is called final class in Java. Final class is complete in nature and can not be sub-classed or inherited. Several classes in Java are final e.g. String, Integer and other wrapper classes.
syntax: final class <class_name>
{

//.................................
}

final classes never participates in inheritance process.But, a inner class may be final or abstract.

0 comments:

Post a Comment