Learn Java With Efficiency: Final Keyword In Java

Profile image for cindy
cindy Software Lead Engineer
Jan 18, 2022 ‧ 2 min read

The final keyword in Java is used to indicate the end of a method, class, or statement. The final keyword cannot be used in JavaScript. The keyword in Java is a programming language feature that can be used to indicate the end of a method, class, or statement. 

 The final keyword in Java is used to restrict the user. The Java final keyword can be used in any context. Final can be: 

  • variable 
  • method 
  • class 

Java final variable 

In Java programming, a final variable is one that cannot hold a reference to any other object. In Java, final variables can be used only in methods. 

Final variables are named like "final int count" or "final float x". They cannot be changed once they are initialized. Final variables need to be declared before using them in any of the methods. 

All other variables can hold references to objects and change as they need to. For example, if you have an object called obj and you want the count to also point at it, you would do something like this: 

final int count = obj.count; 

Example for Final Variable: 

class Bike9{  
 final int speedlimit=90;//final variable  
 void run(){  
  speedlimit=400;  
 }  
 public static void main(String args[]){  
 Bike9 obj=new  Bike9();  
 obj.run();  
 }  
}//end of class  

Java final method 

A final method is a method that cannot be overridden and cannot be implemented by subclasses. 

A final method can only be called from the class that declares it as a final, but any object of the same class can call it. 

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

Output: 

Output: Compile Time Error 

Java final class 

Java final class is a class that can never be sub-classed. It has no superclass and cannot extend any other classes. 

The Java final keyword can be applied to a class definition to indicate that this class cannot be used as a superclass for any other classes and also it will not have any subclasses 

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();  
  }  
}  

output:

Output:running... 
Posted on Jan 18, 2022 by:
Profile image for cindy
cindy
Software Lead Engineer
JavaHTMLSQL.NETXMLVisual Studio

Comments

Profile image for cindy

Software Lead Engineer

JavaHTMLSQL.NETXMLVisual Studio
2.3K
Reputation
139
Following
169
Followers