Wednesday, May 29, 2013

"final" keyword in java (constant in java using "final" Keyword)



Constants in Java:

·         A constant is an identifier whose value will not be changed during the execution of the program.
·         To make a constant in Java, we must use a reserved keyword called “final”.
·         The “final” keyword plays important roles at 3 places. They are:
    • At variable level
    • At method level
    • At class level
  • “final” at variable level:

    • When we don’t want to change the value of a variable, that variable must be made as final variable.
    • Java allows us to declare a final variable and to initialize it later.
      • The “final” variable declaration: when the final variable id declared, one time assignment/initialization is possible and no further modification and assignment are possible.
      • Syntax:
final data-type varName1;
varName1 = val1;
o   Java allows us to declare cum initialize a final variable.
§  When a final variable is declared and initialized then no immediate modifications and assignments are possible.
§  Syntax:
final data-type varName1 = value1;
o   Hence, the final variable value can’t be changed or modified.


  • “final” at method level:

    • When we don’t want to change the definition of a method, that method must be made as final.
    • Syntax:
final returnType methodName(param, if any)
{
            Block of statements
}
o   For example:
Public final float calculateInterest(float p, float r, float t)
{
            return ((p*r*t)/100);
}

o   The definition which is provided in calculateInterest() is fixed i.e. we can’t change it since method is declared as final but we can reuse the method.
o   Hence, the final method can’t be overridden or redifined.


  • “final” at class level:

    • When we don’t want to inherit a class into any other class, then that class must be made as final.
    • Syntax:
final class <ClassName>
{
            Variable declaration
            Method definitions
}
o   For example:
final class C1
{
            int a, b, c;
            public void f1()
            {
                        Block of statements
}
---------------------
---------------------
}

o   Once the class is declared as final, its data members and member methods become final.
o   class C2 extends C1 // Invalid statement.
o   Hence, final class can’t be inherited or reused or extended.
+++++++++++++++++++++++++++++++++++++++++++++++++++

No comments:

Post a Comment