Final Keyword

In the factory a product goes thought may process then we get the final product. It means we don’t want to change it anymore.

The same case is in java.
we can make our methods, class, variable by using final keywords.

Final is a keyword in java which is used to protect methods, class, variable unchanged

Note in java we use final keyword only with:

  • Variable
  • Methods
  • Classes

Final keyword with variable:

When we don’t want to change  our variable after assign value to variable

We use the final keyword with a variable

Example:

class Student{  
final String Force;  
...  
} 

In this Force is a final variable 

If we try to change the final variable it shows error

Final Keyword with methods:

When we don’t want to override our methods. For this, we use the final keyword  with the method

class Human {  
  final void eat(){System.out.println("eating");}  
}  
     
class Boy extends Human{  
   void run(){System.out.println("  running");}  
     
   public static void main(String args[]){  
   Human hum= new Human();  
   hum.eat();  
   }  
}  

In this example eat is a final method in java so we can’t override

Final Keyword with methods:

If we don’t want to extend our class then we make it final

Example

final class Bike{}  
  
class Honda1 extends Bike{  
  void run(){System.out.println("running safely with 100kmph");}  
    
  public static void main(String args[]){  
  Honda1 honda= new Honda1();  
  honda.run();  
  }  
}  

This program show compile-time error if we extend the final class



SHARE THIS PAGE





Important Link