Usage of final keyword in java

Final Keyword In Java



1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It will be constant).
final int  ACK //(generally it is the convention to give capital letters to the final variable we declare)

It dosent occupy space in memory for multiple executions.
Its good that it saves memory 

2) Java final method

If you make any method as final, you cannot override it.

  1. class bird{  
  2.   final void run(){System.out.println("running");}  
  3. }  
  4.      
  5. class animal extends bird{  
  6.    void run(){System.out.println("animals eat birds");}  
  7.      
  8.    public static void main(String args[]){  
  9.    animal lion= new animal();  
  10.    animal.run();  
  11.    }  
  12. }  
if u will test it will have compile error

3) Java final class

If you make any class as final, you cannot extend it.


  1. final class Bike{}  
  2.   
  3. class car extends Bike{  
  4.   void run(){System.out.println("running safely with 100kmph");}  
  5.     
  6.   public static void main(String args[]){  
  7.   car mercedes= new car();  
  8.   car.run();  
  9.   }  
  10. }  

compile time error......


Now question arrises Is final method inherited?

Ans) Yes, final method is inherited but you cannot override it. For Example:

  1. class car{  
  2.   final void run(){System.out.println("running...");}  
  3. }  
  4. class cycle extends car{  
  5.    public static void main(String args[]){  
  6.     new cycle().run();  
  7.    }  
  8. }  


Another question Can we declare a constructor final?

No, because constructor is never inherited.

Comments

  1. Final keyword in java

    Final keyword is mainly used at three places in java; at variable level to make a variable as a constant, at method level to Restrict method overriding, at class level to Restrict inheritance.

    ReplyDelete
    Replies
    1. yes same thing is written based on the concepts you have mentioned

      for variable to make it constant

      for method to avoid overriding

      for class to stop inheritence

      Delete

Post a Comment

Popular posts from this blog

State space search / blocks world problem by heuristic approach /TIC TAC TOE

Navigation in Vaadin.

Drag and drop items from one Grid to another