dsa

Java final keyword

In this tutorial, we will learn about Java final variables, methods and classes with examples.

In Java, the final keyword can be used while declaring an entity. Using the final keyword means that the value can’t be modified in the future. This entity can be - but is not limited to - a variable, a class or a method.

1. Java final Variable

In Java, we cannot change the value of a final variable. If a variable is declared with the final keyword, its value cannot be changed once initialized. Note that the variable does not necessarily have to be initialized at the time of declaration. If it’s declared but not yet initialized, it’s called a blank final variable.

Example :

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

2. Java final method

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!");
    }
}

Example :

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:
   Compile Time Error
      
       

3. Java final classes

When a class is declared with final keyword, it is called a final class. A final class cannot be extended(inherited). There are two uses of a final class :

  1. One is definitely to prevent inheritance, as final classes cannot be extended. For example, all Wrapper Classes like Integer,Float etc. are final classes. We can not extend them.
  2. final class A
    {
         // methods and fields
    }
    // The following class is illegal.
    class B extends A 
    { 
        // COMPILE-ERROR! Can't subclass A
    }
    
  3. The other use of final with classes is to create an immutable class like the predefined String class.You can not make a class immutable without making 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();  
  }  
}  
 
OUTPUT:
   Compile Time Error