Constant in Java
Constant in Java
- A constant in java is used to map and exact and unchanging value to a variable name.
- Final variables are often declared with static keyword in java and treated as constant.
Final keyword in variable declaration:
Syntax: final datatype v1 = val1, v2=val2,----------------------Vn = Valn;
Ex: public static final double PI = 3.14159;
Final keyword in method level:
A java method with final keyword is called final method and it cannot be overridden in sub-class.
Syntax: final returntype methodname(list of formal parameters)
{
block of statements;
}
class PersonalLoan{
public final String getName(){
return "personal loan";
}
}
class CheapPersonalLoan extends PersonalLoan{
@override
public final String getName(){
return "cheap personal loan";
// compilation error: overridden final method
}
Final keyword in class level:
Java class with final modifier is called final class in java. Final class is complete in nature and cannot be sub-classed or inherited
Several classes in java are final e.g. String, Integer, Double and other wrapper classes.
final class PersonalLoan{
}
class CheapPersonalLoan extends PersonalLoan{
// compilation error: cannot inherit from final class
}
Final Keyword allows JVM to optimized method, variable or class.
Few more information on Immutable and Final
- Immutable classes are the one which cannot be modified once it gets created and String is primary example of immutable.
- Immutable classes offer several benefits one of them is that they are effectively read-only and can be safely shared in between multiple threads without any synchronization overhead.
- Final and abstract are two opposite keyword and a final class cannot be abstract in java.
- Final methods are bonded during compile time also called static binding.
- Final variables which is not initialized during declaration are called blank final variable and must be initialized on all constructor either explicitly or by calling this().
- Failure to do so compiler will complain as "final variable (name) might not be initialized".
Comments
Post a Comment