Infolinks In Text Ads

Final Keyword In Java

Final -> Read Only
Assigned value once and only once, Can be used with  variables , methods and Evern Classes.
Final Variables:
A final variable can be assigned value  once at the time of declaration and cannot be re-assign value.

Code Example:


  
package com.aurangzeb.utk;


public class FinalVariable {

     
      // No error declared and initialzed
      public final int a_final=10;
     
     
      // The blank final field b_final may not have been initialized
      // variables must be initialzed at the time of declaration.
     
     
      public final int b_final;
      public int c;
     
      public void finalVariable(){
           
           
            // Error cannot re-assign value to a final variable
           
            a_final =5;
            // can assign value to a non final variable
            c=10;
      }
     
     
}

Final Methods: 
Cannot override the method , cannot override any different Implementation 
Example Code:





package com.aurangzeb.utk;


public class FinalMethod {

      final void cannotOverride(){
           
            System.out.println("Cannot override :Final method");
      }
     
     
     
      // Illegal combination of modifiers abstract and final, a method cannot be both final
      //and abstract
      public final abstract void abstractMethod();
      }
     
     
}


 class child extends FinalMethodClass{
       
       // Error Cannot override a final method
       
       void cannotOverride(){
             
       }
 }

Final Class:

Cannot extends the class, e.g cannot add/modify anything in the class
Appear as a leaf in the Inheritance hierarchy.


Example Code:

 




package com.aurangzeb.utk;

public final class FinalClass {

      public void myMethod(){
           
            System.out.println("A method in the final class");
      }
     
}



class child extends FinalClass{
     
      // compile Time Error cannot inherit from a Final Class
}

 


Newer Post Older Post

Leave a Reply

Powered by Blogger.