Friday, 22 December 2017

Final keyword in java

Final keyword in java,what is final in java. final method in java, final variable in java, final class in java, final method,final variable,final class,

final keyword is used in different contexts. final is a non-access modifier applicable only to a variable, a method or a class.
Following are different contexts where final Keyword  is used.

Final at variable level:-

Final keyword is used to make a variable as a constant. This is similar to const in other language. A variable declared with the final keyword cannot be modified by the program after initialization. This is useful to universal constants
Example:-


Public class Circle
{
Public static final pi=3.141459;
Public static void main(String args[])
{
System.out.println(pi);
}
}

 

Final at method level:-

 

When a method is declared with final keyword, it is called a final method. A final method cannot be overridden. The Object class does this—a number of its methods are final.We must declare methods with final keyword for which we required to follow the same implementation throughout all the derived classes. The following fragment illustrates final keyword with a method:-

class A 
{
    final void m1() 
    {
        System.out.println("This is a final method.");
    }
}
 
class B extends A 
{
    void m1()
    { 
        // COMPILE-ERROR! Can't override.
        System.out.println("Illegal!");
    }
}

 

Final at Class Level:-

We cannot extend a final class. Consider the below example:

Example:-

final class XYZ{                       
}  
                 
class ABC extends XYZ{  
   void demo(){
      System.out.println("My Method");
   }  
   public static void main(String args[]){  
      ABC obj= new ABC(); 
      obj.demo();
   }  
}

 

Points to Remember:- 

 1) constructor cannot be declared as final.

2) Local final variable must be initializing during declaration.
3) All variables declared in an 
interface are by default final.

4) We cannot change the value of a final variable.
5) A final method cannot be overridden.
6) A final class not be inherited.
7) If method parameters are declared final then the value of these parameters cannot be changed.

DashZin

Author & Editor

Has laoreet percipitur ad. Vide interesset in mei, no his legimus verterem. Et nostrum imperdiet appellantur usu, mnesarchum referrentur id vim.

0 comments:

Post a Comment